0

i am looking solution for solve my problem about fixed div when scroll until this same div. I can create script like this:

$(window).scroll(function() {
  if ($(document).scrollTop() > 10) {
      $('.divv').addClass('fixed-top');

  } else {
      $('.divv').removeClass('fixed-top');
  }
});

but script it's only for precise px, i want make fixed div when hit this div, because the content above it's dinamic and change dimensions.

My new working script:

    var elementMap = $('.map-box').offset();
    var elementHeight = $('.calc-height').offset();
    var elementdiffBott = elementHeight.top - $('.map-box').height();

$(window).scroll(function(){
    //alert(elementdiffBott);
        if($(window).scrollTop() > elementMap.top){
            var mapWidth = $('.map-box').width();
              $('.map-box').addClass('gmap-fixed').css('width',mapWidth);
        } else {
            $('.map-box').removeClass('gmap-fixed');
        }    if($(window).scrollTop() > elementdiffBott){
            $('.map-box').removeClass('gmap-fixed');
        }
});
Alberto P
  • 19
  • 6
  • Possible duplicate of [How to detect when the user has scrolled to a certain area on the page using jQuery?](https://stackoverflow.com/questions/7182342/how-to-detect-when-the-user-has-scrolled-to-a-certain-area-on-the-page-using-jqu) – SilverSurfer Jan 24 '19 at 11:14

1 Answers1

1

You can try belo example: In this example, when the div is on your screen it will add fixed-top class to the div

$(window).scroll(function(){
  $('.divv').each(function(){
    if(isScrolledIntoView($(this))){
      $('.divv').addClass('fixed-top');
    }
    else{
      $('.divv').removeClass('fixed-top');
    }
  });
});

function isScrolledIntoView(elem){
    var $elem = $(elem);
    var $window = $(window);

    var docViewTop = $window.scrollTop();
    var docViewBottom = docViewTop + $window.height();

    var elemTop = $elem.offset().top;
    var elemBottom = elemTop + $elem.height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
Prashant Patil
  • 2,020
  • 9
  • 21