MrS1ck
MrS1ck

Reputation: 237

In jQuery, how do I prevent multiple clicks from executing my code multiple times?

For examle, if I had the following code:

$("#divTest").append(variable);

and the intended goal is to display a piece of information once a button was clicked, how do I handle users that are impatient or otherwise feel the need to click more than once (thus producing multiple copies) before the code is executed?

I'll clarify if need be.

Thanks!

Upvotes: 2

Views: 2696

Answers (3)

Turnerj
Turnerj

Reputation: 4278

Look at the jQuery .one function. That would only allow the click handler to be used once.

$("#button").one("click",function() { /* -- Your code here -- */ });

Alternatively, if the button is actually an input or button tag, you could set the disabled attribute. Below is some more information from Mozilla Developer Network (MDN) about the disabled attribute.

This Boolean attribute indicates that the form control is not available for interaction. In particular, the click event will not be dispatched on disabled controls. Also, a disabled control's value isn't submitted with the form.

Upvotes: 5

Hoffmann
Hoffmann

Reputation: 14719

You can also unbind the click event on the first click

$(#button).click(function() {
    $("#divTest").append(variable);
    $(this).off("click");
});

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 121998

in click function

 $("#button").click( function()
           {
              $("#divTest").empty().append(variable);
           }
        );

Upvotes: 3

Related Questions