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:

var myobj = document.getElementById("img_roll_54998");

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

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

myobj.addEventListener("mouseout", function () { myobj.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

Image rollover can be done with pure CSS. See: CSS: Image Rollover.

The advantage of using pure CSS for image rollover is that it's faster, and one less JavaScript code to worry about. The disadvantage is that it's less flexible. You can only have effect with mouse hover. With JavaScript, you can have the effect with any event.

Simple DOM Examples

  1. JS: Change CSS
  2. JS: Change Element's Content
  3. JS: Create HTML Element
  4. JS: 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