Reputation: 10067
I need to attach a submit listener to every form in an iframe but I can't use jQuery.
What's the best way of doing this? I'd rather not use window.onload
because that requires waiting until the images have loaded which may take time. Obviously, $(document).ready()
would have been perfect, but as I said, I can't use jQuery for this.
Thanks
Upvotes: 2
Views: 3027
Reputation: 2861
Onload will do the trick. Martin's jQuery approach will be maybe faster.
for(var i=0; i<document.forms.length; i++){
var form = document.forms[i];
form.addEventListener("submit", myListener,false);
}
Upvotes: 5
Reputation: 26183
Just roll your own :) here is the code that jQuery uses to have the ready event, take what you need, it's free (but do mention in your code where it came from ;)
bindReady: function() {
if ( readyList ) {
return;
}
readyList = jQuery._Deferred();
// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
return setTimeout( jQuery.ready, 1 );
}
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var toplevel = false;
try {
toplevel = window.frameElement == null;
} catch(e) {}
if ( document.documentElement.doScroll && toplevel ) {
doScrollCheck();
}
}
},
Upvotes: 2