Nick Brunt
Nick Brunt

Reputation: 10067

How to attach a submit listener to all forms without jQuery

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

Answers (2)

Jan Pfeifer
Jan Pfeifer

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

Martin Jespersen
Martin Jespersen

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

Related Questions