简体   繁体   中英

Toggle class when object visible in the viewport

I need a script which toggle a class when another class or section is visible in the viewport (during scrolling).

Here I have an script which works for precised distance from top, but can somebody help me to modify it for my needs?

$(window).scroll(function(){
      if ($(this).scrollTop() > 50) {
          $('#viewport').addClass('turn_on');
      } else {
          $('#viewport').removeClass('turn_on');
      }
  });

Working fiddle

Try to add function that detect if element passed in argument is visible :

function isVisisble(elem){
    return $(elem).offset().top - $(window).scrollTop() < $(elem).height() ;
}

$(window).scroll(function(){
   if (isVisisble( $('your_element') ))
      $('#viewport').addClass('turn_on');
   } else {
      $('#viewport').removeClass('turn_on');
   }
});

Hope this helps.

A couple of things. First the scroll event (as well as the resize event) fire multiple times. Traditionally, developers have used something called debouncing to limit the number of times a function fires. I've never got it to work correctly, so instead I check if a condition is met before continuing. You are basically doing this already.

var bool = false
$(window).on('scroll', function(){
   if(!bool){
      bool = true;
      //fire the function and then turn bool back to false.
   };
});

The next thing you need is to identify the element to add the class to. Let's say it has an id of foo .

var yOffset = $('#foo').offset().top;

From here, you'll need to compare the current vertical scroll position with that of the yOffset. You may also need to add the height of the element for when it scrolls out of frame.

var elHeight = $('#foo').height();

The element should be completely in frame with the $(window).scrollTop() equals the yOffset and out of frame when the $(window).scrollTop() is greater than yOffset + elHeight .

This is all assuming the element isn't in the frame to begin with. If it is, it will be trickier but it's a start.

Thx everyone for help. Here I found the solution: LINK

And here is the modified script:

$(document).ready(function () {
    var windowHeight = $(window).height(),
        gridTop = windowHeight * 0.1,
        gridBottom = windowHeight * 1;
    $(window).on('scroll', function () {
        $('.inner').each(function () {
            var thisTop = $(this).offset().top - $(window).scrollTop();

            if (thisTop > gridTop && (thisTop + $(this).height()) < gridBottom) {
                $(this).addClass('on');
            }  
        });
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM