I have an array that contains 5 images. When I mouseover the images I want them to double in size and then return to original size onmouseout. I know how to do this by coding each image individually but I was wondering if there was a way to write one Javascript function (please only Javascript, I'm not allowed to use JQuery for this assignment) that will affect all the images? Here is what I have so far:
My array:
var myImages = new Array("usa.png", "canada.png", "jamaica.png", "mexico.png", "pig.png");
The function I wrote... I'm not sure about the getElements line...:
var doubles = document.getElementsByTagName("img");
doublesWidth = doubles.width;
doublesHeight = doubles.height;
doubles.onmouseover = function() {
doubles.width = 2 * doublesWidth;
doubles.height = 2 * doublesHeight;
}
doubles.onmouseout = function() {
doubles.width = doublesWidth;
doubles.height = doublesHeight;
}
And then in the body I call the images with a height, width and src. For example:
<img id="pig" name="img2" src="pig.png" border="0" height="200" width="350">
Thanks!!!!!
I created a fiddle that here should help you. In the example, it loops over all images and applies event listeners to mouseover
and mouseout
, handling the image size accordingly.
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
images[i].addEventListener("mouseover", function(e) {
e.target.width = e.target.width * 2;
});
images[i].addEventListener("mouseout", function(e) {
e.target.width = e.target.width / 2;
});
}