abcand a link Se...">

Add class when page scrolling by specific identifier

I have an Id in div <div id="Section1"> abc </div> and a link <a id="link" href="#Section1">Section1</a>

Question: When I scroll the page and page on id #Section1 , the class should be added to the link, the link should look like <a id="link" href="#Section1" class="ok">Section1</a>

+6
source share
2 answers

You can use the following:

 $(window).scroll(function (event) { var scroll = $(window).scrollTop(); $('#link').toggleClass('ok', //add 'ok' class when div position match or exceeds else remove the 'ok' class. scroll >= $('#Section1').offset().top ); }); //trigger the scroll $(window).scroll();//ensure if you're in current position when page is refreshed 

See docs for toggleClass .

+4
source

If someone is looking for a good library, I usually use waypoints.js + inview for this type of scroll. It provides a good API to know when items come in and go, etc.

Code example:

 var inview = new Waypoint.Inview({ element: $('#inview-example')[0], enter: function(direction) { notify('Enter triggered with direction ' + direction) }, entered: function(direction) { notify('Entered triggered with direction ' + direction) }, exit: function(direction) { notify('Exit triggered with direction ' + direction) }, exited: function(direction) { notify('Exited triggered with direction ' + direction) } }); 

This requires:

 <script src="/path/to/lib/jquery.waypoints.min.js"></script> <script src="/path/to/shortcuts/inview.min.js"></script> 
0
source

All Articles