Jquery – bind a function as an event handler on a DOM element and remove it once it has been executed

Using JQuery, one can establish a function as an event handler for a given element with the bind() command or with shortcut commands for common events such as click() or change(). Once an event handler is established it will be exucuted anytime the event happens unless it is removed with the unbind() command.

There is however an alternative version of the bind() command in JQuery. The one() command establishes an event handler for a given elelment and removes it automatically once it has been executed. For example:

$('#logo').one('click', function(){
  alert('clicked');
});

Once a user clicks on the #example element, an alert will appear and the event handler will be removed and hence any subsequent clicks on the #example element will not show the allert.

Comments

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • Lines and paragraphs break automatically.

More information about formatting options

5 + 14 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.