Offset () is undefined, but == or === does not think so

The version of jQuery we use is 1.10.2.

On a specific screen, we get a DOM element using jQuery and try to get its offset () object. Sometimes an object may not be displayed and, according to the jQuery documentation, when this case () offset is not supported.

This is good, but what really makes my head spin, why, if I try to check if the offset () object is different than undefined, is the code always included in the condition?

My code (simplified due to non-disclosure agreements) is as follows:

var isCurrent = $('.detail-current[value=\'true\']:first'); if (isCurrent != 'undefined') { var button = isCurrent.closest('.batch-item').find('.batch-item-top').find('input[name=\'edit\']'); var myOffsetTop = 0; if(button.offset() != 'undefined') myOffsetTop = button.offset().top; $('html, body').animate({ scrollTop: myOffsetTop - 50 }); } 

When I debug this using IE development tools, I see on the console that button.offset () is undefined, but button.offset ()! = Undefined returns true !!

Does anyone know why this is happening and how we can better deal with it?

Thanks.

+4
source share
3 answers

You are checking to see if this is a string named undefined , and not really undefined or not.

 if (typeof something === "undefined") alert("something is undefined"); 

To check if it is NULL or not, use if (null === something)

+10
source

You need to check the undefined keyword, not the string "undefined" .

Checking for undefined should look like this:

 if (someVar !== undefined) 

However - if jQuery finds nothing - it does not return undefined. It returns a jQuery object representing an empty set.

Because of this, your first check should use the .length property, for example:

 if (isCurrent.length > 0) 

offset() , on the other hand, makes it return undefined if nothing is defined, so the second check should look like this:

 if (button.offset() !== undefined) 
+5
source

You are not testing undefined, it should be

 if(typeof button.offset() !== 'undefined') 
0
source

Source: https://habr.com/ru/post/1490560/


All Articles