ben
ben

Reputation: 39

Easy JS image changer

I have a simple onMouseOver and Out image changer.

<div id="img1" onMouseOver="changeBg('imgs/1col.png', 'img1')" onMouseOut="changeBg('imgs/1.png', 'img1')"></div>
        <div id="img2" onMouseOver="changeBg('imgs/2col.png', 'img2')" onMouseOut="changeBg('imgs/2.png', 'img2')"></div>

function changeBg (image, id) {
var div = document.getElementById(id);
div.style.backgroundImage = "url("+image+")";

}

However I have like 50 images I would like to apply this effect on, is there an easier way to write this, as a JS function to count automatically and get it to return values etc? so like: "imgs/" + i + "col.png" "img" + i

Thanks for all you help

EDIT: anyone able to help on thiss?

Upvotes: 0

Views: 557

Answers (2)

Midas
Midas

Reputation: 7131

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>

Upvotes: 0

brymck
brymck

Reputation: 7663

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));
});

Upvotes: 1

Related Questions