I'm working my way through a book and the example i'm on is proving to be a bit in-penetrable. Ok, I know there are other simpler ways to achieve the same thing, but this example sets a whole chapter up and so i must do it this way. The code is:
<script type="text/javascript">
/**
* Example 22-1 Adding a rollover effect to an image
*
*
* Add a rollover effect to the specified image, by adding event
* handlers to switch the image to the specified URL while the
* mouse is over the image.
*
* If the image is specified as a string, search for an image with that
* string as its id or name attribute.
*
* This method sets the onmouseover and onmouseout event-handler properties
* of the specified image, overwriting and discarding any handlers previously
* set on those properties.
*
*/
function addRollover(img, rolloverURL) {
if(typeof img=="string") { //If img is a string,
var id = img; //it is an id, not an image
img = null; //and we don't have an image yet.
//first try looking the image up by id
if(document.getElementByID) img = document.getElementByID(id);
else if (document.all) img = document.all[id];
//if not found by id, try looking the image up by name.
if (!img) img = document.images[id];
//If we couldn't find the image, do nothing and fail silently.
if(!img) return;
}
//if we found an element but it is not an <img> tag, we also fail
if(img.tagName.toLowerCase() != "img") return;
//remember the original URL of the image
var baseURL = img.src;
//Preload the rollover image into the browsers cache
(new Image()).src = rolloverURL;
img.onmouseover = function() {img.src = rolloverURL;}
img.onmouseout = function() {img.src = baseURL;}
}
</script>
</head>
<body>
<!-- purley an example
baseURL = images/pirates.jpg
rolloverURL = images/compass.jpg
-->
<img src="images/pirates.jpg" id="MyImg" />
</body>
</html>
The book is 3 years old.
Questions:
After some research I'm thinking
so now my code is:
function addRollover(img, rolloverURL) {
if(typeof img=="string") { //If img is a string,
var id = img; //it is an id, not an image
img = null; //and we don't have an image yet.
//first try looking the image up by id
img = document.getElementByID(id);
//If we couldn't find the image, do nothing and fail silently.
if(!img) return;
}
//if we found an element but it is not an <img> tag, we also fail
if(img.tagName.toLowerCase() != "img") return;
//remember the original URL of the image
var baseURL = img.src;
//Preload the rollover image into the browsers cache
(new Image()).src = rolloverURL;
img.onmouseover = function() {img.src = rolloverURL;}
img.onmouseout = function() {img.src = baseURL;}
}
Before I go any further, is this ok?

New Topic/Question
Reply



MultiQuote





|