Reputation: 961
I have a piece of jQuery and I can't get it done. I have 2 bulletproof vest images. When a button is clicked, 1 will show up. When another is clicked, all vests have to be hidden again first. Now the vests both show up and then 1 disappears.
Here is my example: http://bykwien.nl/soldier/voorbeeld.html
Full preview on JSFiddle: http://jsfiddle.net/8DPCf/
$('#vest1').click(function(){
$('.vest').addClass('hide', function(){
$('.vest1').removeClass('hide');
})
});
$('#vest2').click(function(){
$('.vest').addClass('hide', function(){
$('.vest2').removeClass('hide');
})
});
Upvotes: 0
Views: 69
Reputation: 48415
Quick Fix
I don't think you need to use any callback function for this, just do the 2 calls sequentially like so:
$('#vest1').click(function(){
$('.vest').addClass('hide');
$('.vest1').removeClass('hide');
});
$('#vest2').click(function(){
$('.vest').addClass('hide');
$('.vest2').removeClass('hide');
});
Advanced Solution
In order to make it more generic, allowing for x number of vests you could create a single event handler and determine the vest class using the id
of the clicked button...
Change your button HTML like so (added class):
<div class="item-checkbox vest-button" id="vest1"></div>
<div class="item-checkbox vest-button" id="vest2"></div>
And your javascript as follows:
//add event to all vest elements, and use this to determine which one is clicked
$('.vest-button').click(function(){
$('.vest').addClass('hide');
var className = '.' + $(this).attr("id");
$(className).removeClass('hide');
});
Upvotes: 2
Reputation: 3120
Just remove the callbacks will make the whole thing work, see here:
$('#vest2').click(function(){
$('.vest').addClass('hide', function(){
$('.vest2').removeClass('hide');
})
});
becomes
$('#vest2').click(function(){
$('.vest').addClass('hide');
$('.vest2').removeClass('hide');
});
According to the jQuery documentation, the addClass
method has no callback parameter, which it also doesn't need because it doesn't do anything asynchronically.
Upvotes: 2