Jquery .on() Not Bound When Script Inserted Into The Dom
I have a remote javascript file containing a custom jQuery event handler. When this is inserted into the DOM as a element, the custom event
Solution 1:
You're mistaken. The event handler is being bound when used with a remote script; it simply takes a little longer. The browser needs to make an HTTP request before it binds the handler. This means that the original event you trigger with triggerHandler('customEvent')
is not captured, since its bubbling and capturing has already completed.
If you wait a second, then click the button again, you will see that the event handler has indeed been bound. You can also see this by delaying your triggerHandler
call until the script has loaded:
$('button').click(function() {
var scriptNode = document.createElement('script');
scriptNode.src = 'https://gist.github.com/raw/2767385/897cffca74411dbb542c0713bacb5a4048d6708b/gistfile1.js';
scriptNode.onload = function() {
$('button').triggerHandler('customEvent');
};
document.body.appendChild(scriptNode);
});
Post a Comment for "Jquery .on() Not Bound When Script Inserted Into The Dom"