javascript – Uncaught TypeError: Cannot read property top of undefined

javascript – Uncaught TypeError: Cannot read property top of undefined

Check if the jQuery object contains any element before you try to get its offset:

var nav = $(.content-nav);
if (nav.length) {
  var contentNav = nav.offset().top;
  ...continue to set up the menu
}

Your document does not contain any element with class content-nav, thus the method .offset() returns undefined which indeed has no top property.

You can see for yourself in this fiddle

alert($(.content-nav).offset());

(you will see undefined)

To avoid crashing the whole code, you can have such code instead:

var top = ($(.content-nav).offset() || { top: NaN }).top;
if (isNaN(top)) {
    alert(something is wrong, no top);
} else {
    alert(top);
}

Updated fiddle.

javascript – Uncaught TypeError: Cannot read property top of undefined

The problem you are most likely having is that there is a link somewhere in the page to an anchor that does not exist. For instance, lets say you have the following:

<a href=#examples>Skip to examples</a>

There has to be an element in the page with that id, example:

<div id=examples>Here are the examples</div>

So make sure that each one of the links are matched inside the page with its corresponding anchor.

Leave a Reply

Your email address will not be published.