Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add class when page scroll reach at specific id

Tags:

jquery

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

Question: When I scroll page and page reach at id #Section1 a class should be add in the link, link should like<a id="link" href="#Section1" class="ok">Section1</a>

like image 430
Muhammad Riaz Avatar asked Dec 15 '15 06:12

Muhammad Riaz


1 Answers

You can use like this:

$(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 the docs for toggleClass.

like image 153
Bhojendra Rauniyar Avatar answered Nov 17 '22 05:11

Bhojendra Rauniyar