Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
      }
  });
like image 845
Lukas Avatar asked Jan 24 '26 09:01

Lukas


1 Answers

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.

like image 165
2 revsZakaria Acharki Avatar answered Jan 25 '26 21:01

2 revsZakaria Acharki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!