I want to have an event fire on one click of an element, and then a different event on a second click of the same element. I've attached a demo link below. The problem is that the events are being chained so that one click runs through to the last event without waiting for the second click. I'm sorry if this is a duplicate, but I cannot find the same issue on this board.
I probably haven't worded the question very well, and I'm sure I'm going to get into trouble for it...
$(function(){
l $('.box')
.click(function() {
$(this).removeClass('red'
).addClass('black');
})
.click(function() {
$(this).removeClass('black'
).addClass('blue');
});
});`
http://jsfiddle.net/MEFNG/1/
http://jsfiddle.net/lollero/MEFNG/3/
html:
<div class="box red"></div>
css:
div.box {
width: 100px;
height: 100px;
}
.red {background:red}
.black {background:black}
.blue {background:blue}
jQuery:
$(function(){
$('.box').on("click", function() {
var box = $(this);
if ( box.hasClass('red') ) {
box.removeClass('red').addClass('black');
}
else if ( box.hasClass('black') ) {
box.removeClass('black').addClass('blue');
}
else if ( box.hasClass('blue') ) {
box.removeClass('blue').addClass('red');
}
});
});
use delegation for best performance in this case:
$('.box').parent()
.on('click', '.red', function() {
$(this).removeClass('red').addClass('black');
})
.on('click', '.black', function() {
$(this).removeClass('black').addClass('blue');
});
Of course the syntax could be much better. I use similar to yours to give you a better picture.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With