Marcus wrote:
Below is the HTML including the
bit of Java I am trying to understand why its not working.
Java and javascript are two different languages, platforms etc. They
have nothing in common apart their first 4 letters, so leave java alone
and let's concentrate on javascript:-)
[images rollover]
<a href="messhall.html"
onMouseOver="document.images[1].src='MessHall_on.gif' ;"
onMouseOut="document.images[1].src='MessHall_off.gif' ;"><img
src="MessHall_off.gif" border="0" height="25" width="150"></a><br>
You weren't far, in javascript collections are 0-indexed, try using
document.images[0] instead of document.images[1].
Your way of changing images is probably the most supported, but remains
rather old and hard to maintain; the "rollover" handler is set upon a
link and not the image, because NN4 didn't support mouseover/mouseout
events on images.
If you can yourself determine a naming scheme for your images, then you
could probably do something like the following, which would facilitate
your maintenance and prevent the HTML from growing needlessly.
---
<img src="foo1_off.gif">
<img src="foo2_off.gif">
<img src="foo3_off.gif">
<script type="text/javascript">
function handler(evt){
var p=getImageParts(this);
this.src=p[1]+(p[2]=="on"?"off":"on")+p[3];
}
function getImageParts(img){
//[src, name, on/off, extension] or null
return (/^(.+_)(on|off)(\.[a-z]+)$/i).exec(img.src);
}
window.onload=function(evt){
var g, p;
for(var ii=0,i=document.images; ii<i.length; ii++) {
p=getImageParts(i[ii]);
if(p){
// add the handlers
i[ii].onmouseover=handler;
i[ii].onmouseout=handler;
// preload the alternate image
g=new Image();
g.src=p[1]+(p[2]=="on"?"off":"on")+p[3];
}
}
}
</script>
---
When the page has loaded, a function will iterate all images and add the
relevant mouseover/mouseout handlers; the handler determines
automatically which source is to be set, in regards of the existing source.
The getImageParts function uses "regular expressions" to parse the
source of the image (i.e. to analyze the source string) - here it
"splits" the string into four elements, contained into an array: full
source, image's name, on or off, extension.
Using this approach, you just have to put the javascript anywhere on the
page, and that's it - you can add as many images as you want, the
behavior is already defined for them.
HTH,
Yep.