Simple Image Submit Button Rollovers with jQuery

Friday, 18 April 2008

Have you ever wanted a simple rollover technique with a form submission button? Something like this:

rollover up state

rollover over state

… without having to resort to a complicated mess of javascript form submission and cross browser compatibility issues?

With jQuery it’s really easy. All you need to do is include a standard image form submission tag, like so:

<input type="image" name="submit" id="submit" src="enter.gif">

… and add the hover behavior to the submit input tag. Something like this:

<script type="text/javascript" charset="utf-8">
    $(document).ready(function(){
        $('#submit').hover(
            function(){ // Change the input image's source when we "roll on"
                $(this).attr({ src : 'enter_over.gif'});
            },
            function(){ // Change the input image's source back to the default on "roll off"
                $(this).attr({ src : 'enter.gif'});                }
        );
    });
</script>

This is just a simple example, but you could definitely spruce it up if you needed something more elaborate by adding/removing CSS attributes and the like. Check out the jQuery documentation for more on the hover event.

The benefit of using this method is that the form will be submitted using the standard form submission action, rather than by calling submit() directly through javascript like with other techniques I’ve seen. This has the added benefit that standard form handlers like “onSubmit” will still work whereas, using the submit() method directly will bypass these handlers.


Questions or Comments about this entry?
Send me a message on Twitter (@mirthlab) or via Email.