Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / jQuery

How to Avoid Double Clicking With jQuery ?

5.00/5 (1 vote)
19 Aug 2013CPOL1 min read 61.2K  
Here is how to avoid double clicking with jQuery

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

JavaScript
$("#saveBttn").one("click", function () {
    alert("This will be displayed only once.");
});

OR:

JavaScript
$("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 ==>
JavaScript
$("#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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)