anyone solve this? it's code on minimalistic scrollspy. adds active class when content offset.top. know code works know if there's way change active class "a" tag instead of parent? removed .parent() doesn't seem work. don't want whole li active. in advance.
codepen: https://jsfiddle.net/mekwall/up4nu/
html
<nav class="clearfix"> <ul class="clearfix" id="top-menu"> <li><a href="#services">services</a></li> <li><a href="#aboutus">about us</a></li> <li><a href="#testimonial">testimonials</a></li> <li><a href="#contactus">contact us</a></li> </ul> </nav>
jquery
// cache selectors var lastid, topmenu = $("#top-menu"), topmenuheight = topmenu.outerheight()+15, // list items menuitems = topmenu.find("a"), // anchors corresponding menu items scrollitems = menuitems.map(function(){ var item = $($(this).attr("href")); if (item.length) { return item; } }); // bind click handler menu items // can fancy scroll animation menuitems.click(function(e){ var href = $(this).attr("href"), offsettop = href === "#" ? 0 : $(href).offset().top-topmenuheight+1; $('html, body').stop().animate({ scrolltop: offsettop }, 300); e.preventdefault(); }); // bind scroll $(window).scroll(function(){ // container scroll position var fromtop = $(this).scrolltop()+topmenuheight; // id of current scroll item var cur = scrollitems.map(function(){ if ($(this).offset().top < fromtop) return this; }); // id of current element cur = cur[cur.length-1]; var id = cur && cur.length ? cur[0].id : ""; if (lastid !== id) { lastid = id; // set/remove active class -- part. menuitems .parent().removeclass("active") .end().filter("[href='#"+id+"']").parent().addclass("active"); } });
first added css a.active, because fits [li] space impossible discern active.
then must set starting active tag instead [li]
now can change last 2 javascript rows
menuitems .parent().find('a').removeclass("active") .find('a').end().filter("[href='#"+id+"']").addclass("active");
using find('a') right tag.
Comments
Post a Comment