Search code examples
jquerychaining

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/


Solution

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