39

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);
}
Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
RonLugge
  • 5,086
  • 5
  • 33
  • 61
  • You might want to also look at this: http://stackoverflow.com/questions/2436966/how-would-you-compare-jquery-objects – GnrlBzik Apr 18 '13 at 20:10

3 Answers3

87

You can also do:

 if(val.is(this))
qwertymk
  • 34,200
  • 28
  • 121
  • 184
52

Using the $() function will always create a new object, so no matter what, your equality check there will always fail.

For example:

var div = document.getElementById('myDiv');

$(div) === $(div);   // false!

Instead, you could try just storing the actual DOM elements, since those are just referred to inside jQuery objects.

val = $('#box'+index).get(0);
...
if (this !== val) { }
nickf
  • 537,072
  • 198
  • 649
  • 721
  • 8
    Thanks! As soon as StackOverflow lets me I'll accept this answer. Not only did you answer the question itself, you also explained the conceptual flaw that was screwing me up -- 'give a man a fish, teach a man to fish' – RonLugge Aug 08 '11 at 17:27
  • 4
    this guy taught you how to fish with a fishing pole (lame), the bottom answer teaches you how to fish with your bare hands (BA)! – Dylan Hayes May 21 '15 at 20:02
0

Try this:

function openBox(index)
{
val=$('#box'+index);
$('.profilePageContentBox').each(function(){
    if($(this).is(":visible"))
    {
        if(!$(this).is("#box"+index))
            $(this).slideToggle(200);
    }
});
val.slideToggle(200);
}
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124