Syed
Syed

Reputation: 931

Run jQuery toggle in three parts

I want below jquery code to run in 3 parts.

  1. Part-1, run once only on page load
  2. Part-2, run on 1st click only
  3. Part-3, run on 2nd and any furthur clicking

but it is not running according to my need.

    $('.myClass').toggle(function() {
        alert('Part-1, run once only on page load');
    }, function() {
        alert('Part-2, run on 1st click only');
    }, function() {
        alert('Part-3, run on 2nd and any furthur clicking');
    }).click();

Upvotes: 0

Views: 34

Answers (3)

Pavel Sem
Pavel Sem

Reputation: 1753

  1. Anything what should run once can be run in document ready functionn here
  2. How many times it was clicked can be simply counted in local variable and used in the logic. JQuery click function

JSFiddle

var clickCount = 0;

$(document).ready(function(){
    alert('Part-1, run once only on page load');
})

$('.myClass').click(function() {
    if (clickCount == 0){
        alert('Part-2, run on 1st click only');
    }
    if (clickCount >= 1){
        alert('Part-3, run on 2nd and any furthur clicking');
    }

    clickCount++;
});

Upvotes: 0

Chagai Wild
Chagai Wild

Reputation: 2163

The solution will be to split those callbacks to 2 events, The first event is 'ready' event, in this case:

$(document).on('ready', function() {
    alert('Part-1, run onece only on page load');
});

After that you need to create another event binding:

$('.myClass').one('click', function() { 
    alert('Part-2, run on 1st click only');

   $(this).click(function() { 
      alert('Part-3, run on 2nd and any furthur clicking');
   });
});

The seconds event happens only on the first click, that's when your binding for all later clicks.

Upvotes: 2

Igor Bykov
Igor Bykov

Reputation: 2822

I can't really get what you're trying to finally achieve, but here is the code that does exactly what you described:

jQuery(document).ready(function($) {
    $('.myClass').toggle();
    alert('Part-1, runs once only on page load');

    var isMyClassEverClicked = false;
    $('.myClass').click(function() {
        if (!isMyClassEverClicked) {
            $('.myClass').toggle();
            alert('Part-2, run on 1st click only');
            isMyClassEverClicked = true;
            return;
        }

        $('.myClass').toggle();
        alert('Part-3, run on 2nd and any furthur clicking');
    });
});

Upvotes: 0

Related Questions