I have a jQuery plugin that loads asynchronously and attaches events to a DOM element on page load.
Intermittently the DOM elements are not attached with events from the plugin – This happens due to the loading of these DOM elements via another javascript file.
Is there any way to ensure that event handlers are always attached to DOM elements?
The main answer here is that if you’re writing a plug-in, it’s not your problem to attach it to the right elements on page load (or at any other time). That’s for the user of your plug-in to do. It’s not in your problem domain.
But if you want to try to handle it:
You can ensure that the page is fully loaded by using the jQuery
readyhandler, which has as shortcut (just pass a function intojQuery), e.g.:If you need to handle elements that are added after the page is fully loaded, look at using event delegation. That’s where you handle events not on the elements themselves, but on their ancestor elements, when the events bubble up to them. For instance, this will handle any
clickevent on an element with classfoounless the event is cancelled by a handler attached closer to the element:What
delegatedoes is hook the event on the element you call it on (document.body, in this case), but then only trigger the handler if the actual click had a matching element in the ancestory path from the element where the click actually occurred, to its parent, to its parent, and so on until the element on which you calleddelegate.With recent versions of jQuery, you can also use the hyper-overloaded
onfunction to do the same thing (note the order of the args is different):I prefer
delegatefor clarity.But again, it’s really not your problem. It’s up to the users of the plug-in to know when, and where, to hook it up.