navigation highlight script difficulty

navigation highlight script difficulty

 - I have been playing around with the below peice of code for a while now 

  1. $(document).on("scroll", onScroll);
  2.     
  3.     //smoothscroll
  4.     $('.navbar-nav a[href^="#"]').on('click', function (e) {
  5.         e.preventDefault();
  6.         $(document).off("scroll");
  7.         
  8.         $('.navbar-nav li').each(function () {
  9.             $(this).removeClass('active');
  10.         })
  11.         $(this).addClass('active');
  12.       
  13.         var target = this.hash,
  14.            menu = target;
  15.         $target = $(target);
  16.         $('html, body').stop().animate({
  17.             'scrollTop': $target.offset().top+2
  18.         }, 500, 'swing', function () {
  19.             window.location.hash = target;
  20.             $(document).on("scroll", onScroll);
  21.         });
  22.     });

  23.     function onScroll(event){
  24.     var scrollPos = $(document).scrollTop();
  25.     $('.navbar-nav a').each(function () {
  26.         var currLink = $(this);
  27.         var refElement = $(currLink.attr("href"));
  28.         if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
  29.             $('.navbar-nav li').removeClass("active");
  30.             currLink.addClass("active");
  31.         }
  32.         else{
  33.             currLink.removeClass("active");
  34.         }
  35.     });
  36. }  
  37. });

here is the code in a fiddle :  Jsfiddle

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 ?