The easiest use of one is to pass it an event and a handler like so:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$("#once").one('click',function(){ | |
console.log("click once"); | |
}); |
Click Here to Demo on JS Bin
You can click the link as many times as you wish, however the event will only fire once.
You can pass in more than one event handler to the one function by passing in a list of events separated by a space. When you do this each event will fire once. In this example the event will fire 3 times, one time for each event:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$("#once").one('mousedown mouseup click',function(){ | |
console.log("click once"); | |
}); |
Click Here to Demo on JS Bin
You can also pass in custom data to the event handler, the data comes attached to the event.data object like so:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$("#once").one('click', { color: 'blue', size : 'xxl' }, function(e){ | |
console.log('click once you ' + e.data.size + ' ' + e.data.color + ' rabbit.'); | |
}); | |
}); |
Click Here to Demo on JS Bin
One additional thing you can do with the one function is use an additional selector to pass into the one event that will attach the event to exactly one of the descendants of the matched set. In the following example click on any of the li elements, then click on another, you'll see the event only fires for the first element selected.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$("ul").one('click','li',function( | |
$(this).css('text-decoration','line-through'); | |
}); |
Click Here to Demo on JS Bin
Check out the all of the jQuery function's of the week.