Reputation: 931
I want below jquery code to run in 3 parts.
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
Reputation: 1753
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
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
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