Mouseover multiple images

I want to replicate the code you see below. I want about 5 onmouseover images that change a single image on the end. For example: Image A, B, C, D, E <space space space space> Image F. When you mouseover A, B, C, D, or E, those images change into something else and also change F to a one of five images (depending on whether A, B, C, D, E was mouseovered). Please help.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!--

function roll(img_name1, img_src1, img_name2, img_src2)
   {
   document[img_name1].src = img_src1;
   document[img_name2].src = img_src2;
   }

//-->
</SCRIPT>
</head>

<body>
<A HREF="somewhere.html" onmouseover="roll('sub1', 'movedown.gif', 'sub2', 'an1.gif')" onmouseout="roll('sub1', 'moveup.gif', 'sub2', 'an2.gif')">

<IMG SRC="moveup.gif" NAME="sub1" WIDTH="143" HEIGHT="39" BORDER="0">
</A>

<IMG SRC="an2.gif" NAME="sub2" WIDTH="143" HEIGHT="39">
</body>
</html>

Mmm well here’s one way to do this…

HTML - index.html


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title>Test</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<link rel="stylesheet" type="text/css" href="style.css" />
	<script type="text/javascript" src="script.js"></script>
</head>
<body>
	<div>
		<a id="imgA" onmouseover="change('imgA');" onmouseout="changeReset();" href="#"><img src="1.gif" alt="" /></a>
		<a id="imgB" onmouseover="change('imgB');" onmouseout="changeReset();" href="#"><img src="2.gif" alt="" /></a>
		<a id="imgC" onmouseover="change('imgC');" onmouseout="changeReset();" href="#"><img src="3.gif" alt="" /></a>
		<a id="imgD" onmouseover="change('imgD');" onmouseout="changeReset();" href="#"><img src="4.gif" alt="" /></a>
		<a id="imgE" onmouseover="change('imgE');" onmouseout="changeReset();" href="#"><img src="5.gif" alt="" /></a>
	</div>
	<div id="target"></div>
</body>
</html>

CSS - style.css


#target { width: 100px; height: 100px; border: 1px solid #aaa; }

.a { background: #000; }
.b { background: #ff0000; }
.c { background: #0000ff; }
.d { background: #ff7800; }
.e { background: #aaa; }

JavaScript - script.js


function change(v) {
	var target = document.getElementById("target");
	if (v == "imgA") {
		target.className = "a";
	} else if (v == "imgB") {
		target.className = "b";
	} else if (v == "imgC") {
		target.className = "c";
	} else if (v == "imgD") {
		target.className = "d";
	} else if (v == "imgE") {
		target.className = "e";
	} else {
		target.className = "";
	}
}
function changeReset() {
	var target = document.getElementById("target");
	target.className = "";
}

(JavaScript isn’t really my thang, by the way.) :stuck_out_tongue:

OK, so what’s basically going on is in the HTML file, there are 5 images: imgA, imgB, imgC, imgD, and imgE. When a mouse goes over any of those images, #target’s color changes depending on which image you hovered over.

In the JavaScript, there are two functions. The first function, change(), checks the argument it just got passed, and changes #target’s class to one that corresponds with the argument. So…if you sent, say, “imgA,” then it gives #target the class of “a.” The colors change because of the CSS supplied. Each different class: .imgA, .imgB, .imgC, .imgD, and .imgE has a different color.

In your case, you wanted different images to show up in place of #target, so all you have to do is alter the CSS. I didn’t, however, make it so each image changes when you hover over them. If you want to, alter your CSS a bit using things like #imgA:hover { } or something.

It shouldn’t be too complicated, although my random rambling may have confused you (sorry if it did). You can take the code and play around with it a bit.

Hope it helps.

You’'ll be wanting these things

  • storage for the image to use on mouseover and mouseout
  • event registration for the mouseover and mouseout
  • functions for mouseover and mouseout that set the appropriate image
  • a function that sets the end image, depending on the currently hovered image

The best place to store the image names of mouseover and mouseout is on the image itself. The scriptinf for that should not be within the HTML itself, but contained in the script file.

When we move over we’re wanting to change two images, and when we move out we’re wanting to change another two images, so that can form the bases of the storage structure.


var mouseImages = [
    {over: 'movedown1.gif', overend: 'an1.gif', out: 'moveup1.gif', outend: 'an2.gif'},
    {over: 'movedown2.gif', overend: 'an3.gif', out: 'moveup2.gif', outend: 'an4.gif'}
];

When the page is loading, we can go through the images and attach these values to the image elements that they apply for. This makes it easier to obtain the information at some later time.

When we come across an image that we’re going to work with, we can set the onmouseover and onmouseout events too.


var container = document.body; // it's better to use getElementById()
var images = document.getElementsByTagName('img');
for (var i = 0; i< images.length; i++) {
    for (var rollover in mouseImages) {
        if (rollover.out == images[i].getAttribute('src')) {
            images[i].roll = rollover.out;
            images[i].onmouseover = rollOver;
            images[i].onmouseout = rollOut;
        }
    }
}

And now we can perform the actual actions in the rollOver() and rollOut() functions


function rollOver() {
    var endImage = document.getElementById('endImage');
    this.setAttribute('src', this.roll.over);
    endImage.setAttribute('src', this.roll.overend);
}
function rollOut() {
    var endImage = document.getElementById('endImage');
    this.setAttribute('src', this.roll.out);
    endImage.setAttribute('src', this.roll.outend);
}

Wow. I didn’t expect anybody to answer. Let alone within hours. I am very much thankful to both of you for helping me. I haven’t tried out the second posting’s script, but I just wanted to express my gratitude. Thanks!!!

I have a few questions:

For Niki, thanks again. How do I make it so that in changes the image as opposed to the color of the square? I assume something like “.a { img: image.jpg; }”? Also, how can I also make it a hyperlink so that when it is clicked it takes the viewer to another page?

For pmw57, thanks again as well. I was a bit lost but I’m waiting patiently for your next post after your testing.

@jscript: My unobtrusive technique appears to work fine.

If the images are encapsulated in a div or a table, it would be better to use an identifier for that area then reference that area with


var container = document.getElementById('myGallery');

The rest of it is fairly self explanitory. While it’s possible to use lots of identifiers to reference the elements, it’s better to not use them, which allows you to more easily change the HTML at will.

With the array, it is possible to reference those values by making it a global variable, but it’s even better if we don’t pollute the global namespace, and store the information instead on the element that the event is going to be fired on.


var mouseImages = [
    {over: 'movedown1.gif', overend: 'an1.gif', out: 'moveup1.gif', outend: 'an2.gif'},
    {over: 'movedown2.gif', overend: 'an3.gif', out: 'moveup2.gif', outend: 'an4.gif'}
];
var container = document.getElementById('myGallery');
var images = document.getElementsByTagName('img');
for (var i = 0; i< images.length; i++) {
    for (var rollover in mouseImages) {
        if (rollover.out == images[i].getAttribute('src')) {
            images[i].roll = rollover.out;
            images[i].onmouseover = rollOver;
            images[i].onmouseout = rollOut;
        }
    }
}

When the event is fired, the this keyword refers to the element itself that the event occurred on. Because the information is already stored there, we can easily access it to perform the image changes.


function rollOver() {
    var endImage = document.getElementById('endImage');
    this.setAttribute('src', this.roll.over);
    endImage.setAttribute('src', this.roll.overend);
}
function rollOut() {
    var endImage = document.getElementById('endImage');
    this.setAttribute('src', this.roll.out);
    endImage.setAttribute('src', this.roll.outend);
}

You said before that you felt a bit lost about things. Can you please expand on that so we can clear things up for you.

Background images can be applied with CSS by:


.a { background: url(/* Image name */) no-repeat; }

To direct users to another page, just type in the location you want to link to in the anchor tags.

I recommend you use pmw57’s script, though, it’s very good. :cool:

Hi pmw57, I think I’m confused because I don’t know how the three javascript sections interact with the HTML. Can you post the entire code (the javascript coding and then the img tags)? I don’t see how it all fits. Thanks again and Niki as well.


...
<body>
<div id="imgGallery">
    <p>
        <img src="moveup1.gif">
        <img src="moveup2.gif">
    </p>
    <img src="an2.gif">
</div>
<script src="rolloveImage.js"></script>
</body>
</html>

I’m really really sorry, but can you put the entire thing together for me? I’m not that experienced :frowning: . I tried this and it didn’t work:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script>
var container = document.getElementById('myGallery');
var mouseImages = [
    {over: 'movedown1.gif', overend: 'an1.gif', out: 'moveup1.gif', outend: 'an2.gif'},
    {over: 'movedown2.gif', overend: 'an3.gif', out: 'moveup2.gif', outend: 'an4.gif'}
];
var container = document.getElementById('myGallery');
var images = document.getElementsByTagName('img');
for (var i = 0; i< images.length; i++) {
    for (var rollover in mouseImages) {
        if (rollover.out == images[i].getAttribute('src')) {
            images[i].roll = rollover.out;
            images[i].onmouseover = rollOver;
            images[i].onmouseout = rollOut;
        }
    }
}
function rollOver() {
    var endImage = document.getElementById('endImage');
    this.setAttribute('src', this.roll.over);
    endImage.setAttribute('src', this.roll.overend);
}
function rollOut() {
    var endImage = document.getElementById('endImage');
    this.setAttribute('src', this.roll.out);
    endImage.setAttribute('src', this.roll.outend);
}
</head>

<body>
<div id="imgGallery">
    <p>
        <img src="menu1.bmp">
        <img src="menu2.bmp">
    </p>
    <img src="menu3.bmp">
</div>
<script src="rolloveImage.js"></script>
</body>
</html>

The script should be placed at the bottom of the page, just before the closing body tag.

There are some problems with placing scripts in the head. Even though we’ve been taught to do them that way, placing them at the end of the document provides several benefits.

Best Practices for Speeding Up Your Web Site

That’s super interesting! Thanks for the link.

If scripts are placed at the bottom, it doesn’t necessarily mean the HTML and all the DOM elements will load up first, does it?

Yes it does, because by the time the browser has processed down to the script, the areas above it have been loaded into the DOM already.

From perhaps the most knowledgeable JavaScript programmer around, Douglas Crockford

<script src=“filename.js”> tags should be placed as late in the body as possible. This reduces the effects of delays imposed by script loading on other page components. There is no need to use the language or type attributes. It is the server, not the script tag, that determines the MIME type.

From Code Conventions for the JavaScript Programming Language