JS DOM: 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

Code

<img id="img_nsyh" src="i/tile_A.png" alt="tile A">
{
 const img_nsyh = document.getElementById("img_nsyh");

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

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

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

 img_nsyh.addEventListener("mouseover", f_toB);
 img_nsyh.addEventListener("mouseout", f_toA);
}

Image Rollover