Easy JS Image Changer
I have a simple onMouseOver and Out image changer.
Solution 1:
The HTML:
<!-- Easier to add event handlers at once programmatically -->
<div id="img1">a</div>
<div id="img2">b</div>
The JavaScript (note that I'm using jQuery):
// Retrieve URL from ID
function imgUrlFromId(id, toggle) {
var id = id.replace("img", "");
return "url(imgs/" + id + (toggle ? "col" : "") + ".png)";
}
// Create function defining how to build the URL to the replacement images
function changeImage(e) {
$(e.currentTarget).css("backgroundImage",
imgUrlFromId(e.currentTarget.id, (e.type === "mouseover")));
}
// Bind mouseover and mouseout event handlers to each div with an ID
// starting with "img"
$("div#[id^=img]").each(function() {
$(this).mouseover(changeImage).mouseout(changeImage)
.css("backgroundImage", imgUrlFromId(this.id, false));
});
Solution 2:
TADA
JavaScript:
window.onload = function() {
div = document.getElementById('images').getElementsByTagName('div');
j = 1;
for (i = 0; i < div.length; i++) {
if (div[i].className == 'img') {
div[i].setAttribute('id', j);
div[i].style.backgroundImage = 'url(' + j + '.png)';
div[i].onmouseover = function() {
this.style.backgroundImage = 'url(' + this.getAttribute('id') + 'col.png)';
}
div[i].onmouseout = function() {
this.style.backgroundImage = 'url(' + this.getAttribute('id') + '.png)';
}
j++;
}
}
}
HTML:
<div id="images">
<div class="img"></div>
<div class="img"></div>
<div class="img"></div>
<div class="img"></div>
<div class="img"></div>
<div class="img"></div>
<div class="img"></div>
<div class="img"></div>
<div class="img"></div>
<div class="img"></div>
... for as many images you want
</div>
Post a Comment for "Easy JS Image Changer"