'Using jQuery one() function as a hack to prevent multiple click events from firing
I've having this weird issue where toggling the visibility of a button seems to influence how many times a click event gets called on that button.
If I use: $('button').on('click'...)
, to click the button only 1 click event happens as long as prior to clicking it I had done a full page load. If instead, I load a page fragment containing the button via AJAX then click the button, the on()
function fires off multiple click events, an added one for every time I load the page this way.
I can limit these multiple clicks from firing by using $('button').one('click', ...
But i'm wondering if this is too hack-ish and it'd be better to fix what's causing the multiple click events from firing in the first place.
Has any run into this problem before of toggling visibility -/+ AJAX page loading affecting how many click events get fired on a click handler?
Solution 1:[1]
I guess its not at all hack-ish
coz the very first line of the jQuery Docs for One() describe the purpose this function is designed for.
Attach a handler to an event for the elements. The handler is executed at most once per element.
This easily says that it prevents multiple raises of events.
The internal working principle of this function is also same as mentioned by @mgraph, its mentioned in the docs:
The first form of this method is identical to .bind(), except that the handler is unbound after its first invocation. The second two forms, introduced in jQuery 1.7, are identical to .on() except that the handler is removed after the first time the event occurs at the delegated element, whether the selector matched anything or not.
A bit more detail -
This method normally binds an event to a handler using .bind()
/.on()
and as soon as the event occurs once and only once, it unbinds the event using .unbind()
/.off()
Solution 2:[2]
If you're loading an element via AJAX, you want to use .on()'s binding property to tie it to an element that exists when the page loads. For example, $("body").on("click", "p", ...
will bind the click element to p tags not only when the page has loaded, but also after any AJAX calls. If you simply do $("p").on("click", ...
this only binds the click event to p elements when the page had loaded. So in the first example, you pick a parent element (hopefully more specific than the body) of the element you want to bind to, and then specify the element within the call to .on(). So in your case you may want to try, $('body').on('click','button', ...)
.
Oh, and as a side note, as of jQuery 1.7, the .on() and .off() methods are preferred to attach and remove event handlers on elements over .bind() and .unbind().
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | j08691 |