Reputation: 1172
In case that there is an objects called (id) "ABC123", I want to scroll down automatic to that object. That works fine if this object exist. But if not, I receive an error: "TypeError: $(...).offset(...) is undefined"
My code should avoid this error, but doesn't work:
if(typeof($('#ABC123')) != 'undefined') {
$('html, body').animate({ scrollTop: ($("#ABC123").offset().top-100) }, 0).scroll();
}
Upvotes: 0
Views: 279
Reputation: 14827
A jQuery object will never be null
or undefined
, even you're not passing any argument $()
, In this case it's just empty and simply do nothing.
Seem like you want to check whether it's empty or not:
if ($('#ABC123').length) {
$('html, body').animate({ scrollTop: ($("#ABC123").offset().top-100) }, 0).scroll();
});
Upvotes: 0
Reputation: 382464
The jQuery collection is never undefined
.
Simply test that it's not empty :
if ($('#ABC123').length) {
Upvotes: 4