Search code examples
jqueryhtmljquery-3

Event on First click, Second click, and Third click


$('#element').toggle(function(){
  $(this).addClass('one');
},
                     function(){
  $(this).removeClass('one').addClass('two');
},
                     function(){
  $(this).removeClass('two').addClass('three');
});
#element{
  width: 150px;
  height: 150px;
  border: 1px solid #000;
}
.one{
  background: orange;
}
.two{
  background: blue;
}
.three{
  background: red;
}
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<div id="element"></div>

Hi, I am trying to develop the UI on the base of three clicks on the same id, heres the code which i was trying. But when I'm rendering it, I was getting the error as

`Uncaught TypeError: r.easing[this.easing] is not a function
    at init.run (jquery-3.1.1.min.js:3)
    at i (jquery-3.1.1.min.js:3)
    at Function.r.fx.timer (jquery-3.1.1.min.js:3)
    at hb (jquery-3.1.1.min.js:3)
    at HTMLDivElement.g (jquery-3.1.1.min.js:3)
    at Function.dequeue (jquery-3.1.1.min.js:3)
    at HTMLDivElement.<anonymous> (jquery-3.1.1.min.js:3)
    at Function.each (jquery-3.1.1.min.js:2)
    at r.fn.init.each (jquery-3.1.1.min.js:2)
    at r.fn.init.queue (jquery-3.1.1.min.js:3)`

can any one help me in solving it. I googled but dint found the solution.

Thanks.

CSKADMIN


Solution

  • Just Replace your jQuery with this:

    var flag = 0, existing_class = '';
    var class_value = ['one', 'two', 'three'];
    $('#element').click(function(){
        if(flag <= 2)
        {
            $(this).removeClass(existing_class);
            $(this).addClass(class_value[flag]);
            existing_class = class_value[flag];
        }
        flag++;
    });
    

    OR

    If you want to call repetitive 'one', 'two', 'three' class then you should try below code:

    var flag = 1, existing_class = '';
    var class_value = {1 : 'one', 2 : 'two', 3 : 'three'};
    $('#element').click(function(){
        $(this).removeClass(existing_class);
        if(flag > 3) {
            $(this).addClass(class_value[flag % 3 === 0 ? 3 : flag % 3]);
            existing_class = class_value[flag % 3 === 0 ? 3 : flag % 3];
        } else {
            $(this).addClass(class_value[flag]);
            existing_class = class_value[flag];
        }
        flag++;
    });