user2279081
user2279081

Reputation: 77

Prevent Multiple Clicks in JQuery

I am creating a dynamic quiz and I need to prevent multiple clicks on my 'next' button. In the click function I tried to an if condition to prevent multiple clicks. Not sure why it doesn't work. Would greatly appreciate some help.

var nextButton= $('<button/>', {
    text: 'Next', 
    id: 'nextButton',
    click: function (event) {
        event.preventDefault();

        if($("#container").filter(':animated').length>0) {
                  return false;
            }

        /* rest of code*/
     }
});

Here is the code as it appears my JSFiddle of my application

Bonus Question: I was told event.preventDefault() is good practice. Is this true? If so, why?

Update: The JSFiddle line # where the code above is line 81 in case you want to mess around with the code without digging through it all.

Upvotes: 5

Views: 6529

Answers (4)

Ashish Rawat
Ashish Rawat

Reputation: 3513

One way to do this to use timeStamp property of event like this to gap some time between multiple clicks:

var a = $("a"),
    stopClick = 0;


a.on("click", function(e) {
  if(e.timeStamp - stopClick > 300) { // give 300ms gap between clicks
     // logic here

    stopClick = e.timeStamp; // new timestamp given
  }


});

Upvotes: 2

Khanh TO
Khanh TO

Reputation: 48972

var nextButton= $('<button/>', {
    text: 'Next', 
    id: 'nextButton',
    click: function (event) {
        event.preventDefault();

        if($("#insideContainer").filter(':animated').length>0) {
                  return false;
            }

        /* rest of code*/

     }
});

I found out why. You're checking against the wrong element. It should be #insideContainer Demo

Upvotes: 2

Praveen
Praveen

Reputation: 56509

Try to use event.stopImmediatePropagation() to prevent multiple clicks.

Desc: Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree.

Upvotes: 0

Pank
Pank

Reputation: 14268

Try like this

$("#id or .class").one("click",function(){
  // your activity
});

Description:

The one() method attaches one or more event handlers for the selected elements, and specifies a function to run when the event occurs.

When using the one() method, the event handler function is only run ONCE for each element.

Upvotes: 2

Related Questions