J P
J P

Reputation: 65

Inside a click event, fire code once on first click, remaining code runs on all clicks

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

Answers (2)

Pranav C Balan
Pranav C Balan

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

Rick Hitchcock
Rick Hitchcock

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

Related Questions