Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 601
user2279081 Avatar asked Jun 08 '13 07:06

user2279081


People also ask

How do you make button click only once in JavaScript?

There are a number of ways to allow only one-click in Javascript: Disable the button after clicking on it. Use a boolean flag to indicate “clicked”, don't process again if this flag is true. Remove the on-click attribute from the button after clicking once.


3 Answers

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

like image 184
Khanh TO Avatar answered Oct 18 '22 20:10

Khanh TO


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.

like image 40
Pank Avatar answered Oct 18 '22 21:10

Pank


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
  }


});
like image 25
Ashish Rawat Avatar answered Oct 18 '22 19:10

Ashish Rawat