Reputation: 65
How do I run a piece of code only on the first click of a button but also have the remaining code run on all clicks?
$button.click(function (e) {
// Only run on first click
$element.removeClass('mobile').addClass('desktop');
// Run on every click
$elementTwo.show()
});
Upvotes: 1
Views: 54
Reputation: 115222
Just use a Boolean flag variable
var st = true;
$button.click(function(e) {
// this line only execute once, since after first execution `st` will update to false
st && $element.removeClass('mobile').addClass('desktop') && st = false;
$elementTwo.show()
});
Upvotes: 2
Reputation: 35670
Use jQuery's one() method:
$button.one('click', function() { //this will run only on the first click
$element.removeClass('mobile').addClass('desktop');
});
$button.click(function() { //this will run for every click
$elementTwo.show();
});
Upvotes: 1