views:

230

answers:

4

I have a list of items that can be hidden/unhidden via JS be clicking them. The currently open item is stored in a variable, openActivity. Only one item can be opened at a time. I want to check in the click() event whether the clicked item is the same as the already opened item, so that it does not do a double-animation of it closing and then opening. I would suspect this to work at first:

if (openActivity == $(this)) alert('hello');

But it does not. I noted this does not work either:

if ($(this) == $(this)) alert('hello'); //never alert()s !

Here's all most relevant code, if it's worth anything to you (you may not have to look at this):

openActivity = null;
$('.activityOuterContainer').click(function () {
    if (openActivity !== null) {
     if (openActivity == $(this)) alert('hello');
     activityExtra(openActivity).slideUp();
     activityToggle(openActivity).css('background-position', '0 0');
    }
    openActivity = $(this);
    activityExtra(openActivity).slideDown();
    activityToggle(openActivity).css('background-position', '0 -20px');
});


function activityToggle(a) {
    return a.closest('.activityOuterContainer').find('.activityToggle');
}
function activityExtra(a) {
    return a.closest('.activityOuterContainer').find('.activityExtra');
}

And one of the items:

<div class="activityOuterContainer">
    <div class="activityContainer">
     <div class="activityFormContainer">
      name here
      <div class="activityExtra">
       <p>extra</p>
      </div>
     </div>
     <div class="activityIsUsed">checkbox here</div>
    </div>
    <div class="activityToggle"></div>
</div>
A: 

Could give them all ID's and then just check that?

Noon Silk
+5  A: 

I would use addClass() for marking the opened and you can check that easily.

Santi
A: 

Like silky or Santi said, a unique ID or class would be the easiest way to test. The reason your if statements don't work like you'd expect is because it's comparing 2 objects and seeing if they're the same object in memory.

Since it's always a new object getting created by $(this), they can never equal each other. That's why you have to test on a property of the object. You could get away with no unique id/class if each openActivity element was guaranteed to have different content that you could test against.

Pat
+5  A: 

This should work:

if ($(this)[0] === $(this)[0]) alert('hello');

so should this

if (openActivity[0] == $(this)[0]) alert('hello');
epascarello