Pergunta

I have a question on rollover effects using JavaScript.

I have read that image sprites (image with another image on its side) can be used with help of CSS offsetting to achieve basic rollover when onmouseover is handled using JS. Have also read about the possibility of changing classes itself using JS (className) to achieve the above effect.

My question is, can I modify the image src itself using JavaScript, to achieve the rollover effect?

A code like this, maybe -

document.getElementByID("button1").onmouseover = rolloverFunction;
function rolloverFunction(){
this.src = "button1-image2.png";
}

I typed something like this to see if the src of the image can be modified upon rollover, but it is not working. Could you please let me know where I am going wrong?

Foi útil?

Solução

You need the mouseover and mouseout events. mouseover is triggered when hovering in the image, mouseout on leaving the image. Using plain ol' JS would yield:

<img src="default.png" id="image" alt="">

<script>
var image = document.getElementById("image");
image.onmouseover = function () {
    this.src = "rollover.png";
};
image.onmouseout = function () {
    this.src = "default.png";
};
</script>

Or using a common function to avoid duplicating the URL:

function rollover_effect(img_elm, rollover_src) {
    var default_src = img_elm.src;
    img_elm.onmouseover = function () {
        img_elm.src = rollover_src;
    };
    img_elm.onmouseout = function () {
        img_elm.src = default_src;
    };
}
rollover_effect(document.getElementByID("image"), "rollover.png");
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top