Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compare two jQuery objects for identity?

I'm trying to use jQuery to open / close control 'boxes' on a webpage. Unfortunately, it doesn't look very good to close a box just to re-open it if the user happens to click on the already opened box. (Boxes are mutually exclusive).

The code I'm using doesn't work, and I'm not sure why. I still get a box closing just to open up anew, which isn't the desired functionality. I created the 'val' variable for debugging purposes; in the debugger, it shows 'val' as having the exact same value as $(this), which should prevent it from getting to the .slideToggle() inside the if statement, but doesn't.

function openBox(index) {   val = $('#box' + index);   $('.profilePageContentBox').each(function(){       if($(this).css('display') != 'none')       {         if($(this) != val)         {           $(this).slideToggle(200);         }       }     });   val.slideToggle(200); } 
like image 820
RonLugge Avatar asked Aug 08 '11 17:08

RonLugge


People also ask

How do you compare two values of objects?

In Java, the == operator compares that two references are identical or not. Whereas the equals() method compares two objects. Objects are equal when they have the same state (usually comparing variables). Objects are identical when they share the class identity.

How does object comparison work in JavaScript?

Objects are not like arrays or strings. So simply comparing by using "===" or "==" is not possible. Here to compare we have to first stringify the object and then using equality operators it is possible to compare the objects.


1 Answers

You can also do:

 if(val.is(this)) 
like image 170
qwertymk Avatar answered Sep 21 '22 20:09

qwertymk