javascript - Highlighting the sidebar links with scroll -
i have side bar settings page index. want appropriate links highlight every time scroll different section of page. realize has been asked before, , tried doing told in previous question . looked @ couple of blogs, though code seems quite complicated.
html
<div id="sidebar"> <nav class="navlinks"> <ul style="list-style:none" id="sidebar-id"> <li> <a href="#profile-settings"> profile </a></li> <li> <a href="#social-settings"> social media </a></li> <li> <a href="#"> logout </a></li> /ul> </nav> </div> <section id="profile-settings"> <!--some content--> </section> <section id="social-settings"> <!--some content--> </section> css:
.active { color:red; } js
$(document).ready(function () { $(document).scroll(function () { var scroll_top = $(document).scrolltop(); var div_one_top = $('#profile-settings').position().top; var div_two_top = $('#social-settings').position().top; if(scroll_top > div_one_top && scroll_top < div_two_top) { //you past div 1 $('a[href="#profile-settings"]').addclass('active'); $('a[href="#social-settings"]').removeclass('active'); } else if (scroll_top > div_two_top) { $('a[href="#social-settings"]').addclass('active'); $('a[href="#profile-settings"]').removeclass('active'); } }); }); when run though, <li> <a href="#profile-settings">profile</a></li> shows active class, constantly, meaning wont change when scroll bottom or top. second li(#social settings) wont have .highlight class added @ all. i'm new javascript , jquery, , grateful help. thank in advance.
you missed < </ul>.when add < /ul>,everything in browser.
adding console.log(div_one_top,div_two_top); console.log(scroll_top); before ifstatement,you can check data console.
Comments
Post a Comment