The issue is that the click event occurs after the loop has finished, so the value of 'x' is no longer the value it would be within the loop.
eg when x is 3, it adds an event to .deal3
but when it's clicked, x now = 6 so it toggles .deal6
.
This is why you can use this
inside the event handler.
var x = 0;
for (x = 1; x <= 6; x++) {
jQuery('.deal' + x).click(function(){
jQuery(this).toggleClass('open');
});
};
In the case where you're clicking a button that's a child element, you still use this
, but now this
is the button, so use .closest()
to find the relevant container:
var x = 0;
for (x = 1; x <= 6; x++) {
jQuery('.deal' + x + ' .iw-so-media-box').click(function(){
jQuery(this).closest(".deal").toggleClass('open');
});
}
in this case, I would add a second class (as shown above), giving your html as:
<div class='deal deal1'>
<div>deal 1</div>
<button class='iw-so-media-box' type='button'>toggle</button>
</div>
However, if you've done that anyway, then just get rid of the loop completely and add your event handler to .deal
:
jQuery('.deal .iw-so-media-box').click(function() {
jQuery(this).closest(".deal").toggleClass('open');
});
.deal>div {
display: none;
}
.deal.open>div {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='deal deal1'>
<div>deal 1</div>
<button class='iw-so-media-box' type='button'>toggle</button>
</div>
<div class='deal deal2'>
<div>deal 2</div>
<button class='iw-so-media-box' type='button'>toggle</button>
</div>
<div class='deal deal3'>
<div>deal 3</div>
<button class='iw-so-media-box' type='button'>toggle</button>
</div>