Description: Attach a handler to an event for the elements. The handler is executed at most once per element.
.one( eventType, [ eventData ], handler(eventObject) )
version added: 1.1
eventType
A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names.
eventData
A map of data that will be passed to the event handler.
handler(eventObject)
A function to execute each time the event is triggered.
This method is identical to .bind(), except that the handler is unbound after its first invocation. For example:
$('#foo').one('click', function() {
alert('This will be displayed only once.');
});
After the code is executed, a click on the element with ID foo will display the alert. Subsequent clicks will do nothing. This code is equivalent to:
In other words, explicitly calling .unbind() from within a regularly-bound handler has exactly the same effect.
Examples
Example 1
Tie a one-time click to each div.Example 1 - Full source:
<!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript" language="javascript"> $(document).ready(function(){ var n = 0; $("div").one("click", function(){ var index = $("div").index(this); $(this).css({ borderStyle:"inset", cursor:"auto" }); $("p").text("Div at index #" + index + " clicked." + " That's " + ++n + " total clicks."); }); }); </script> <style> div { width:60px; height:60px; margin:5px; float:left; background:green; border:10px outset; cursor:pointer; } p { color:red; margin:0; clear:left; } </style> </head> <body> <div></div> <div></div> <div></div> <div></div> <div></div> <p>Click a green square...</p> </body> </html>
Example 2
To display the text of all paragraphs in an alert box the first time each of them is clicked:Example 2 - Full source:
<!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript" language="javascript"> $(document).ready(function(){ $("p").one("click", function(){ alert( $(this).text() ); }); }); </script> </head> <body> <p>Paragraph 1</p> <p>Paragraph 2</p> <p>Paragraph 3</p> <p>Paragraph 4</p> <div></div> <p>Click a paragraph...</p> </body> </html>
Was this information helpful?

