Rollovers with JavaScript

Move your mouse over the image below. It should change. This is called a "rollover" or a "hover button." JavaScript is used with two images to make an image link change when a mouse moves over it.

Example rollover image

JavaScript Code

Here is the JavaScript code for the example above:

<script type="text/javascript">
<!--
    if (document.images) {
        image_off = new Image(295, 106);
        image_off.src = "images/rollover1.gif";
        image_on = new Image(295, 106);
        image_on.src = "images/rollover2.gif";
    }

    function over(imageName) {
        if (document.images) {
            document[imageName].src = eval(imageName + "_on.src");
        }
    }

    function out(imageName) {
        if (document.images) {
            document[imageName].src = eval(imageName + "_off.src");
        }
    }
// -->
</script>

HTML Code

<a
    href="#top"
    onmouseover="over('image')"
    onmouseout="out('image')"
    ><img
        src="images/rollover1.gif"
        name="image"
        width="295"
        height="106"
        alt="Example rollover image"
        /></a>

This is some simple HTML with a bit of JavaScript to catch the onmouseover event and the onmouseout event. This means that when the mouse passes over the image, the function over will be called. When the mouse leaves the image, the function out will be called.

Multiple Rollovers

For multiple image rollovers you need to give the images different name attributes and give the over and out function calls the appropriate parameters.