Easily manage mouseovers with javascript
This is a short tutorial in which I first show you a small js file I wrote to manage mouseovers on my site and I will then break it down step by step.
The purpose of the script is to use javascript and the DOM to find all the images on the page that have a classname of 'MsOvrs' (the class we will give any images that have an associated mouseover image) and then apply an onmouseover and an onmouseout event to each.
Let's have a look at the javascript function
Now let\'s break it down
In the first line of the function we define a variable 'x' and give it the value of document.getElementsByTagName('img'). getElementsByTagName creates an array, each item of which refers to an element of the type defined (in this case img).
We can now refer to any img tag in the document in the following way:
On the next line of the function we define a new array and place it in a variable called 'preload'. We populate this array with all the mouseover images so that they can be preloaded into the visitors browser.
The next step is to tell the script to run through the array of img tags so as to assess which have a classname of 'MsOvrs'.
We do this with the use of a 'for' loop.
Now for each run through the 'for' loop we want to check the class of the element. To do this we simply use an 'if' statement.
Once the script has verified that an element does conform to the conditions applied (it is an image and it does have classname=...) it needs to get the src attribute of the element. We place this into a var (imSrc) so that we can reference it again in the mouseOut function.
We also need to get the src attribute of the mouseover image. To do this I use a naming convention; Any mouseover, mouseout pair are always named in the following way:
imName.gif, imName_over.gif
myimage.png, myimage_over.png
and so on.
We can then use the javascript 'replace' method to get our mouseover image src attribute
Next we create an instance of the mouseover image in the browser cache so our visitors do not need to wait for it to load when they place the mouse over it
And finally we create the onmousover, onmouseout events for the element.
Can you think of a reason why x[i] would cause an error if we used it inside one of the onmouse... events?
By the time the actual events are fired the for loop in our function will have long since finished running and - since the 'i' variable is being incremented on every iteration of the loop - by the time the event is actually triggered 'x[i]' will = x[x.length] not x[i]
For this reason also - inside the onmouseover/out functions - we must once again go through the process of replacing all instances of .gif etc. in the images src attribute with _over.gif.
