Skip to content Skip to sidebar Skip to footer

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 --><divid="img1">a</div><divid="img2">b</div>

The JavaScript (note that I'm using jQuery):

// Retrieve URL from IDfunctionimgUrlFromId(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 imagesfunctionchangeImage(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:

<divid="images"><divclass="img"></div><divclass="img"></div><divclass="img"></div><divclass="img"></div><divclass="img"></div><divclass="img"></div><divclass="img"></div><divclass="img"></div><divclass="img"></div><divclass="img"></div>
    ... for as many images you want
</div>

Post a Comment for "Easy Js Image Changer"