Home javascript Error: “Cannot read property 'top' of undefined” while creating scroll

Error: “Cannot read property ‘top’ of undefined” while creating scroll




In theory like this

var destination = jQuery ("# ​​job"). offset (). top;
if (jQuery.browser.safari) {
  jQuery ('body'). animate ({scrollTop: destination}, 1100); // 1100 - scrolling speed
} else {
  jQuery ('html'). animate ({scrollTop: destination}, 1100);
return false;

Should work, but nothing will scroll. jQuery is included. Writes,

Cannot read property ‘top’ of undefined

Question from answer @ Alexey Dementyev .

Answer 1, authority 100%

In this case, jQuery ("# ​​job"). offset () – returns undefined , which is only possible if jQuery ("# ​​job ") did not find any elements that match the selector.

In addition, depending on the version of jQuery, when using this method, null may also be returned, hence the error may change to

Uncaught TypeError: Cannot read property ‘top’ of null (…)

Answer 2

Try to call the function inside $ (document) .ready (), the element may not have loaded yet

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions