JS: Image Rollover

By Xah Lee. Date: . Last updated: .

This page shows a JavaScript based 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="img_roll_54998" src="i/tile_A.png" alt="tile A">

Here's the JavaScript code:

let obj = document.getElementById("img_roll_54998");

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

obj.addEventListener("mouseover", (() => { obj.src="i/tile_B.png"; }) , false);

obj.addEventListener("mouseout", (() => { obj.src="i/tile_A.png"; }) , false);

How to pre-cache Images?

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

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

Pure CSS Image Rollover

CSS: Image Rollover

Simple DOM Examples

  1. JS: Change CSS
  2. DOM: Change Element's Content
  3. DOM: Create HTML Element
  4. DOM: Remove HTML Element

  1. JS: document.write
  2. JS: Image Rollover
  3. JS: Pop-up New Window
  4. JS: Digital Clock
  5. JS: Stopwatch
  6. JS: Fade a Element
  7. JS: Fade a Element Using CSS Transition
  8. JavaScript UI: Shake Element
  9. JS: How to Create Tooltip
  10. JS: Falling Snow Effect
  11. JavaScript Floating Box Following Scroll
Like what you read? Buy JavaScript in Depth