Introduction
There has been a troubling issue regarding user interaction, when the user double clicks the DOM elements. Such as always buttons, links, etc. Fortunately, jQuery has an awesome solution for this. That is .one()
method
What does .one Method Do?
It attaches a handler to an event for the elements and that handler is executed at most once per element.
Theory
.one( events [, selector ] [, data ], handler(eventObject) )
events
Type: String
- One or more space-separated event types and optional namespaces, such as "
click
" or "keydown.myPlugin
"
selector
Type: String
- A selector string to filter the descendants of the selected elements that trigger the event
- If the selector is
null
or omitted, the event is always triggered when it reaches the selected element
data
Type: Anything
- Data to be passed to the handler in
event.data
when an event is triggered
handler(eventObject)
Type: Function()
- A function to execute when the event is triggered
- The value
false
is also allowed as a shorthand for a function that simply does return false
Example
$("#saveBttn").one("click", function () {
alert("This will be displayed only once.");
});
OR:
$("body").one("click", "#saveBttn", function () {
alert("This displays if #saveBttn is the first thing clicked in the body.");
});
Key points of the above code are listed below:
- After the code is executed, a click on the element with Id
saveBttn
will display the alert - Subsequent clicks will do nothing
- This is equivalent to ==>
$("#saveBttn").on("click", function (event) {
alert("This will be displayed only once.");
$(this).off(event);
});
In other words, explicitly calling .off()
from within a regularly-bound handler has exactly the same effect.
Do You Need to Know More ?
Conclusion
The above mentioned method works since jQuery Version 1.7. So if your element's click event fires more than once, then this may be the solution. Enjoy this awesome method and let me know if you have any issues.
You Might Also Like