Page is a not externally linkable
- Code, Content, and Presentation
-- JavaScript and AJAX
---- Need help with JavaScript


Fotiman - 1:13 pm on Jul 7, 2010 (gmt 0)


Here's how I would do it.

First, don't use the language attribute on script tags. It's invalid. Use the type attribute instead.

Next, don't use HTML comments inside of the script tags. They haven't been needed for many, many years.

Use lowercase letters for tags and attributes (<img> instead of <IMG> and onmouseover instead of onMouseOver).

Rather than create a fragile system that is dependent on files being named with certain numbers, I would opt for a more explicit approach, where you specify exactly what items you want to work on. I would do this by creating a map of element ids (an id value to be assigned to each image) to the images you want to use on those elements. Also, I would use progressive enhancement to keep the markup as pure as possible, so no inline event handlers. Behavior is managed entirely in the JavaScript code.

Here's what I came up with:


<!DOCTYPE html>
<html>
<head>
<title>Image mouseover/out test</title>
</head>
<body>
<!--
Each image gets a unique id. It doesn't matter what the name of
each image file is... they could be org0.jpg, foobar.jpg, 010110.jpg
-->
<img src="org0.jpg" id="img1">
<img src="org1.jpg" id="img2">
<img src="org2.jpg" id="img3">
<!--
It would be preferable to put this in an external script file but
for the sake of this example I'm including it in the HTML document.
Either way, put this at the END of the document, just before the
closing body tag to ensure we can find the images in the document.
-->
<script type="text/javascript">
(function () {
var el,
id,
imgSwap = { // Create the map of id to images
img1: { oldImg: 'org0.jpg', newImg: 'new0.jpg' },
img2: { oldImg: 'org1.jpg', newImg: 'new1.jpg' },
img3: { oldImg: 'org2.jpg', newImg: 'new2.jpg' }
};
for (id in imgSwap) {
if (imgSwap.hasOwnProperty(id)) {
el = document.getElementById(id);
if (el) {
// Attach event handlers
el.onmouseover = function (el, src) {
return function () {
el.src = src;
};
}(el, imgSwap[id].newImg);
el.onmouseout = function (el, src) {
return function () {
el.src = src;
};
}(el, imgSwap[id].oldImg);
}
}
}
})();
</script>
</body>
</html>


With that example, you specify in your JavaScript code exactly what images you want to work on. The id attribute of your images ("img1", "img2", etc.) matches the property of the imgSwap object.


Thread source:: http://www.webmasterworld.com/javascript/4165486.htm
Brought to you by WebmasterWorld: http://www.webmasterworld.com