matt
matt

Reputation: 101

TypeError: .offset(...) is undefined

can't understand whats wrong whit my code. Im my js:

var full_url = window.location.href;
    var parts = full_url.split("#");
    var trgt = parts[1];
    if (trgt) {
        var aTag = jQuery("a[name='" + trgt + "']");
        jQuery('html,body').animate({scrollTop: aTag.offset().top}, 'slow');

I get this error:

TypeError: aTag.offset(...) is undefined ...jQuery("html,body").animate({scrollTop:aTag.offset().top},"slow")}}jQuery("body"...

The url is something like this:

http://www.myurl/my-link/#backnumber

Im my html:

<a name="backnumber"></a>

Thanks

Upvotes: 1

Views: 2205

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074545

This tells you that as of when the

var aTag = jQuery("a[name='" + trgt + "']");

line ran, there was no matching element, and so jQuery gave you back an empty set. When you call offset() on an empty set, you get back undefined, and so you get an error trying to read its .top property.

Upvotes: 1

Related Questions