navigation highlight script difficulty
- I have been playing around with the below peice of code for a while now
- $(document).on("scroll", onScroll);
-
- //smoothscroll
- $('.navbar-nav a[href^="#"]').on('click', function (e) {
- e.preventDefault();
- $(document).off("scroll");
-
- $('.navbar-nav li').each(function () {
- $(this).removeClass('active');
- })
- $(this).addClass('active');
-
- var target = this.hash,
- menu = target;
- $target = $(target);
- $('html, body').stop().animate({
- 'scrollTop': $target.offset().top+2
- }, 500, 'swing', function () {
- window.location.hash = target;
- $(document).on("scroll", onScroll);
- });
- });
-
- function onScroll(event){
- var scrollPos = $(document).scrollTop();
- $('.navbar-nav a').each(function () {
- var currLink = $(this);
- var refElement = $(currLink.attr("href"));
- if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
- $('.navbar-nav li').removeClass("active");
- currLink.addClass("active");
- }
- else{
- currLink.removeClass("active");
- }
- });
- }
- });
-
now if you have a look at the if condition in the onScroll function :
if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos)
somehow this consition fails and the message i get in the console is
TypeError: refElement.position(...) is undefined
i get the same error in firefox and also in firebug .
getting that message would mean , the condition failed , but ironically the next line still execute I.E.
$('.navbar-nav li').removeClass("active");
how is that possible and why am i getting this error message ?