I tried to work with waypoints.js
and make menu element active, when user scroll to it. As I can see, waypoints works well, but I can't get current section id
... Console always said undefined
.
So, what I'm doing wrong?
My script is:
jQuery(function() {
var sections = jQuery('section');
var navigation_links = jQuery('nav a');
sections.waypoint({
handler: function(direction) {
var active_section;
active_section = jQuery(this);
if (direction === "up") active_section = active_section.prev();
var active_link = jQuery('nav a[href="#' + active_section.attr("id") + '"]');
navigation_links.parent().removeClass("active");
active_link.parent().addClass("active");
active_section.addClass("active-section");
console.log(active_section.attr("id"))
},
offset: '35%'
});
});
My HTML nav
is:
<ul class="nav">
<li><a href="#home">Home</a></li>
<li><a href="#spec">What we do</a></li>
<li><a href="#features">Features</a></li>
<li><a href="#tools">Tools</a></li>
<li><a href="#contacts">Contacts</a></li>
</ul>
My HTML section
is:
<section id="home">
<div class="wrap">
<h1>...</h1>
</div>
</section>
As mentioned by @AmmarCSE the problem is indeed with
if (direction === "up") active_section = active_section.prev();
. Basically if the previous element does not have anid
thenundefined
will be printed in the console. A way to avoid this is to check that the previous element has anid
(check and make sure it's notundefined
), an only then setactive_section
like so:Example Here