javascript - Active anchor tag changes on scroll using a id and a name -
as stated in title, having issues trying figure out how work. know there several examples of out there, not apply doing or code have.
i'm pretty deep project , cannot start over, have of accomplished cannot work when user scrolls on page , anchor tag in menu changes it.
is there simple solution using latest jquery , javascript coincide , ?
or going have literally start on over project?
here bit of code on have:
<nav id="menu" class="menu"> <a class="menu-trigger"></a> <ul> <li><a href="#">:: join community ::</a></li> <li><a href="#home_wrapper" class="active">home</a></li> <li><a href="#about_wrapper">about</a></li> <li><a href="#advertise_wrapper">advertise</a></li> <li><a href="#central_wrapper">gp central</a></li> <li><a href="#contact_wrapper">contact</a></li> <li><a href="#career_wrapper">career</a></li> <li><a href="#press_wrapper">press</a></li> <li><a href="#">:: dashboard ::</a></li> </ul> </nav> <div id="main_body"> <div id="about_wrapper"> </div> <div class="clear"></div> <div id="advertise_wrapper"> </div> <div class="clear"></div> <div id="central_wrapper"> </div> <div class="clear"></div> <div id="contact_wrapper"> </div> <div class="clear"></div> <div id="career_wrapper"> </div> <div class="clear"></div> <div id="press_wrapper"> </div> </div>
i've tried this:
$(window).scroll(function() { var windscroll = $(window).scrolltop(); $('.page').each(function(i) { var postop = $(this).position().top, h = $(this).height(); if (postop <= windscroll && postop + h > windscroll ) { $('.menu ul li').removeclass('active'); $('.menu ul li').eq(i).addclass('active'); } }); });
any appreciated!
found answer of 4dgaurav!
var sections = $('div') , nav = $('.menu') , nav_height = nav.outerheight(); $(window).on('scroll', function () { var cur_pos = $(this).scrolltop(); sections.each(function() { var top = $(this).offset().top - nav_height, bottom = top + $(this).outerheight(); if (cur_pos >= top && cur_pos <= bottom) { nav.find('a').removeclass('active'); sections.removeclass('active'); $(this).addclass('active'); nav.find('a[href="#'+$(this).attr('id')+'"]').addclass('active'); } }); }); nav.find('a').on('click', function () { var $el = $(this) , id = $el.attr('href'); $('html, body').animate({ scrolltop: $(id).offset().top - nav_height }, 500); return false; });
Comments
Post a Comment