Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError jQuery offset().top is undefined

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.

like image 284
K7Buoy Avatar asked Jan 31 '14 10:01

K7Buoy


People also ask

What is offset() top in jQuery?

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.

What does offset do in javascript?

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.


1 Answers

It 's because your $(".navbar") cannot be found. Check if the element exist before getting offset.

if ($(".navbar").length) {...} 
like image 51
user3709748 Avatar answered Oct 02 '22 20:10

user3709748