Javascript - Cannot Read Property 'top' Of Null
I have function that scrolls to a anchor position in a list function snapToAnchor(anchor) { $('#divProductScroll').scrollTop(0); var offset = $(anchor).offset().top - $(
Solution 1:
The anchor variable does not contain a valid selector for you site. Calling offset
on this will return null
.
Example
var a = $('#non-existing-id'); //returns empty objectvar b = a.offset(); // returns null
b.top; //throws a TypeError exception
You can simply debug your program by inserting alert(anchor)
on line 3. This will show you the contents of the variable.
Solution 2:
if anchor has id of the DOM element - then correct way to use it with jQuery:
$('#' + anchor).offset()
otherwise you'll get a null (and error).
Solution 3:
$(anchor).offset().top
will usually output a string not a number... something like 100px. you need to extract the number from the string.
var topoffset = $(anchor).offset().top;
topoffset = topoffset.split('px', 1);
Post a Comment for "Javascript - Cannot Read Property 'top' Of Null"