0

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();
    }
1
  • make sure you mark the correct answer with a green check mark Commented Apr 7, 2013 at 16:33

2 Answers 2

4

The jQuery collection is never undefined.

Simply test that it's not empty :

if ($('#ABC123').length) {
Sign up to request clarification or add additional context in comments.

Comments

0

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();
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.