The Firefox debugger is showing a TypeError for a jQuery function aimed at sticking a navbar to the to the top of the page when a user scrolls and updating the class at the same time.
The function is below.
$(window).scroll(function() { if ($(".navbar").offset().top>30) { $(".navbar-fixed-top").addClass("sticky"); } else { $(".navbar-fixed-top").removeClass("sticky"); } });
The resulting error is this.
Timestamp: 31/01/2014 10:01:04
Error: TypeError:
$(...).offset(...)
is undefined
I have looked about on SO for a similar example but can not translate the outcomes into a fix. Any help would be greatly appreciated.
The offset() method set or returns the offset coordinates for the selected elements, relative to the document. When used to return the offset: This method returns the offset coordinates of the FIRST matched element. It returns an object with 2 properties; the top and left positions in pixels.
offset() method allows us to retrieve the current position of an element (specifically its border box, which excludes margins) relative to the document. Contrast this with . position() , which retrieves the current position relative to the offset parent.
It 's because your $(".navbar") cannot be found. Check if the element exist before getting offset.
if ($(".navbar").length) {...}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With