Pergunta

i am creating a very simple Javascript rollover effect: mouseover a word and it swaps an image on the page. mouseOut and it returns to the original image. As a newcomer to JavaScript I was thrilled when I understood enough to make the initial swap occur. How to return to the original image on mouseOut eludes me. The baby code:

<head>
<script>
function mOver(obj)
{
document.getElementById("img1").src="image2.jpg";
}

function mOut(obj)
//not certain what goes here…..
</script>
</head>

<body>

     <div>
    <p1 onmouseover="mOver(this)" onmouseout="mOut(this)"> ROLLOVER </p1>
     </div>

     <div id="image">
    <img id="img1" src="image1.jpg" alt="imag1">
     </div>

</body>

My understanding of the above: rolling over the p1 tag causes a mouseOver event handler to call a function which (using the DOM) switches the source attributes of the original image to make image switch. It doesn't seem possible to do the reverse on the mouseOut, because the swapped image (not being in the document) can not be addressed with a proper id. I'm sure there are multiple ways to do this. If anyone could help this youngster out, I'd appreciate it. I am very interested in furthering my knowledge in Javascript.

Foi útil?

Solução

Your understanding of sequence is correct: event happens, event is handled by function, function changes source of the image

But when you change the image .src you do not change the ID - DOM element <img> remains the same, only its source changed, so you can still access it by the original ID:

function mOut() {
   document.getElementById("img1").src="image1.jpg";
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top