Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery prevent other events after a click

Tags:

jquery

I am trying to prevent multiple clicks on links and items, which is causing problems.

I am using jQuery to bind click events to buttons (jQuery UI) and image links (<a><img /></a>).

Is there a way to do-once-for-all prevent other events from firing after a click occurs?

Or do I have to maintain a global variable called _isProcessing and set it to true for each event handler?

Thanks

Edit: (clarification) Thanks for your answers, my problem isn't preventing the bubbling of the event, but preventing multiple concurrent clicks.

like image 374
Russell Avatar asked Aug 12 '10 23:08

Russell


People also ask

What is the use of stopPropagation in jquery?

stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed. Tip: Use the event. isPropagationStopped() method to check whether this method was called for the event.

How do I stop click event propagation?

To stop the click event from propagating to the <div> element, you have to call the stopPropagation() method in the event handler of the button: btn. addEventListener('click', (e) => { e. stopPropagation(); alert('The button was clicked!

What is event preventDefault () in jquery?

The event. preventDefault() method stops the default action of an element from happening. For example: Prevent a submit button from submitting a form. Prevent a link from following the URL.


1 Answers

There are various ways to prevent concurrent clicks from running the code.

One way is to unbind('click') on the element, then .bind() it again when you're ready.

I'd rather use some sort of flag. It could be a variable, but I'd rather assign a class to the element, like .processing, and remove it when done. So you would have the handler check for the existence of that class to determine of the code should run.

$('someElement').click(function() {     var $th = $(this);     if($th.hasClass('processing'))           return;     $th.addClass('processing');     // normal code to run     // then when done remove the class     $th.removeClass('processing'); }); 

Another option is to use the elements .data() to set a similar flag, like $(this).data('processing', true); Then set it to false when done.

like image 134
user113716 Avatar answered Sep 23 '22 01:09

user113716