Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to chain multiple click events on same element in JQuery?

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/

like image 672
user1199178 Avatar asked Dec 26 '22 10:12

user1199178


2 Answers

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');
        }

    });

});
like image 82
Joonas Avatar answered Feb 06 '23 10:02

Joonas


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.

like image 20
Eru Avatar answered Feb 06 '23 09:02

Eru