LAshooter said:
I have a portfolio page which loads a dozen thumbnails and one large image.
A friend helped me code a script (below) which will swap out the large image
(named "imgLarg") when a different thumbnail is clicked. Both the thumbnail
and the enlargement are identically named, one is in /thumbs/ and one is in
/enlargements/ - tricky, huh? ;-) What's the easiest way to make this work
in other browsers as well?
<script language="JavaScript">
The language attribute is deprecated, type is required:
function enlarge() {
oSrcElem = event.srcElement;
Your use of 'event' (i.e. the event object) here is one factor that makes
your script IE-centric. There are two basic event models: W3C and IE [1].
But there is no need to use the event object at all - you can pass a
reference directly from the element clicked on using 'this'.
On your thumbnail, use an onclick attribute like:
<img onclick="enlarge(this);" ... >
then:
function enlarge (oSrcElem){
// ...
Now oSrcElem is a reference to the element that fired the click event
without using the event object. Using 'this' is much more reliable and
consistent across various browsers.
imgLarge.src = oSrcElem.src.replace(/thumbs/,'images');
Here 'imgLarge' is either the name or id of the large image element, right?
And there you have your second IE-centric bit of code. IE makes all
element names and ID properties of the global object, a rather silly idea
that causes all sorts of problems.
In other browsers, you can get a reference to a named image using the
images collection (part of DOM 0), so in Firefox:
document.images.imgLarge
is a reference to the the image element with a name or ID of 'imgLarge'.
For some unknown reason, IE doesn't support that, you have to use the index
number. So if imgLarge is the 5th image in the document:
document.images[4]
would do the trick (and would work in Firefox too).
Anyhow, you are probably best to use getElementById with fall back to
document.all if you want to support IE 4. Try the following:
function enlarge (oSrcElem)
{
var imgLarge;
if (document.getElementById){
imgLarge = document.getElementById('imgLarge');
} else if (document.all){
imgLarge = document.all['imgLarge'];
}
if (imgLarge){
imgLarge.src = oSrcElem.src.replace(/thumbs/,'images');
}
While compiling the above, it occurred to me that it may be OK to use:
function enlarge (oSrcElem)
{
if (!imgLarge && document.getElementById){
var imgLarge = document.getElementById('imgLarge');
}
if (imgLarge){
imgLarge.src = oSrcElem.src.replace(/thumbs/,'images');
}
}
Untested. Of course anyone without scripting will see nothing happen.
1. Read about the different event models here:
<URL:
http://www.quirksmode.org/js/introevents.html>