JS: Image Rollover

By Xah Lee. Date: . Last updated: .

This page shows a JavaScript based image rollover.

This technique is used around 1999. Today, you should use pure CSS based image rollover instead, see CSS: Image Rollover

Move your mouse to the following image and see it change. (on mobile devices, touch the image also works.)

tile A

Here's the HTML code:

<img id="img75439" src="i/tile_A.png" alt="tile A">

Here's the JavaScript code:

{
const img75439 = document.getElementById("img75439");

// pre-cache
(new Image()).src = "i/tile_B.png";

const f_toA = (() => { img75439.src="i/tile_A.png"; });

const f_toB = (() => { img75439.src="i/tile_B.png"; });

img75439.addEventListener("mouseover", f_toB , false);

img75439.addEventListener("mouseout", f_toA , false);
}

How to pre-cache Images?

(new Image()).src = "cats.png";

the Image() is a constructor that returns a HTMLImageElement object, which represents the <image> element.

DOM How-To


Web Scripting Overview


HTML Input


Web Scripting Examples


Web Scripting Misc


jQuery


node.js

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials