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.
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.
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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With