Preventing Multiple Clicks in JQuery

I am creating a dynamic quiz and I need to prevent a few clicks on my "next" button. In the click function, I tried to fulfill the if condition to prevent several clicks. I don’t know why this is not working. I would really appreciate your 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, it seems to me, my JSFiddle of my application

Bonus Question: I was told that event.preventDefault() is a good practice. It's true? If so, why?

Update: Line JSFiddle # , where the code above is line 81 , if you want to communicate with the code without digging it all.

+4
source share
4 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 are checking the wrong item. This should be the #insideContainer Demo

+2
source

try it

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

Description:

The one () method attaches one or more event handlers for the selected elements and sets the function that is executed when the event occurs.

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

+1
source

One way to do this is to use the t20> property of such an event so that the time interval between several 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 } }); 
+1
source

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

Desc: Keeps the rest of the handlers running and prevents bubbles from appearing in the DOM tree.

0
source

Source: https://habr.com/ru/post/1485154/


All Articles