Sometimes, we want to disable links to stop double-clicks in jQuery.
In this article, we’ll look at how to disable links to stop double-clicks in jQuery.
Disable Links to Stop Double-Clicks in jQuery
To disable links to stop double-clicks in jQuery, we can add an attribute to the elements we want to disable after 1 click.
Then we can return false
is those elements are clicked again.
For instance, if we have:
<a class='button' href='#'>foo</a>
<a class='button' href='#'>bar</a>
Then we write:
$("a.button").click(function() {
$(this).attr("disabled", "disabled");
});
$(document).click(function(evt) {
if ($(evt.target).is("a[disabled]"))
return false;
});
We select the a
elements with class button
with $("a.button")
.
Then we call click
to add a click event listener that adds the disabled
attribute to them if they’re clicked.
Next, we add a click listener to document
.
In the click listener, if the element is an a
element with the disabled
attribute, we return false
so nothing is done.
Conclusion
To disable links to stop double-clicks in jQuery, we can add an attribute to the elements we want to disable after 1 click.
Then we can return false
is those elements are clicked again.