Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

offset() is undefined but == or === does not think so

The jQuery version that we are using is 1.10.2.

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

This is all fine but, what's really making my head spin is why if I try to check if the offset() object is different than undefined the code always goes inside the condition?

My code (simplified because of non-disclosure agreements) is like 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 anybody know why this happens and how we could best handle it?

Thank you.

like image 913
Sergio Romero Avatar asked Dec 07 '22 06:12

Sergio Romero


2 Answers

You are checking if it is a string called undefined, not whether it is actually undefined or not.

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

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

like image 162
Zevi Sternlicht Avatar answered Dec 08 '22 21:12

Zevi Sternlicht


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

A check for undefined should look like this:

if (someVar !== undefined)

However - if jQuery doesn't find something - it does not return undefined. It returns a jQuery object representing an empty set.

Because of that, your first check should use the .length property, like this:

if (isCurrent.length > 0)

offset(), on the other hand does return undefined if there's nothing defined - so your second check should look like this:

if (button.offset() !== undefined)
like image 22
jcsanyi Avatar answered Dec 08 '22 19:12

jcsanyi