Reputation: 1852
I wrote some jQuery that checks the location of the person on the page and add some classed.
But when I load the jQuery I see a lot of errors in the browser console. When scrolling the number of errors increase.
I get the following error:
TypeError: undefined is not an object (evaluating 'refElement.position().top')
Geselecteerd element
How can I solve this?
jQuery:
(function($) {
$(window).scroll(function() {
var sticky = $('.menu-header-product'),
scroll = $(window).scrollTop();
var elementOffset = jQuery("#productnav").offset();
if (scroll >= elementOffset.top - 88) sticky.addClass('sticky');
else sticky.removeClass('sticky');
});
$(window).scroll(function() {
var sticky = $('.content'),
scroll = $(window).scrollTop();
var elementOffset = jQuery("#productnav").offset();
if (scroll >= elementOffset.top - 88) sticky.addClass('sticky');
else sticky.removeClass('sticky');
});
$(document).ready(function() {
$(document).on("scroll", onScroll);
$('a[href^="#"]').on('click', function(e) {
e.preventDefault();
$(document).off("scroll");
$('a').each(function() {
$(this).removeClass('active');
})
$(this).addClass('active');
var target = this.hash;
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top - 88 /**just subtract the height of the fixed html part */
}, 500, 'swing', function() {
window.location.hash = target;
$(document).on("scroll", onScroll);
});
});
});
function onScroll(event) {
var scrollPosition = $(document).scrollTop();
$('nav a').each(function() {
var currentLink = $(this);
var refElement = $(currentLink.attr("href"));
if (refElement.position().top - 88 <= scrollPosition && refElement.position().top - 125 + refElement.height() > scrollPosition) {
$('nav ul li a').removeClass("active");
currentLink.addClass("active");
}
else {
currentLink.removeClass("active");
}
});
}
})(jQuery.noConflict());
Upvotes: 0
Views: 122
Reputation: 15639
You have not written any style for your .active
class,
I have just added a color:red
to it and it seems to work fine.
Working DEMO: https://jsfiddle.net/pytduk9q/3/
Hope this helps!
Upvotes: 1