1

I've looked at similar questions and answers on Stack Overflow which I can't get to work. everything is find when the page loads but when I mouse over it doesn't show the new gif.

When inspecting the code in the browser it seems to be switching between the two images.

<!DOCTYPE html>
<html>
<head>
<script>


function normalImg() {
  document.getElementById("smile").src = "/smiley.gif"
}
function singing() {
  document.getElementById("smile").src = "/sing.gif"
}

</script>
</head>
<body>


<img onmouseout="normalImg()" border="0" src="smiley.gif" alt="Smiley" width="32" height="32" id="smile" 
onmouseover="singing()" border="0" src="sing.gif" alt="singing" width="32" height="32">


<p>onmouse out and onmouseover changing images</p>

</body>
</html>
halfer
  • 19,824
  • 17
  • 99
  • 186
Ryan JT
  • 70
  • 2
  • 12

3 Answers3

1

you should have only one src attribute inside < img /> tag, you could try the code below:

<!DOCTYPE html>
<html>
<head>
<script>


function singing() {
  document.getElementById("smile").src = "https://upload.wikimedia.org/wikipedia/commons/0/06/180717_%EC%97%B4%EB%A6%B0%EC%9D%8C%EC%95%85%ED%9A%8C_%ED%8A%B8%EC%99%80%EC%9D%B4%EC%8A%A4_%2818%29.jpg"
  document.getElementById("smile").alt="smiling"
}

function crying() {
  document.getElementById("smile").src = "https://upload.wikimedia.org/wikipedia/commons/c/cd/Chou_Tzuyu_at_the_Golden_Disc_Awards_2019.png"
  document.getElementById("smile").alt="crying"
}

</script>
</head>
<body>


<img onmouseover="singing()" onmouseout="crying()" src="https://upload.wikimedia.org/wikipedia/commons/c/cd/Chou_Tzuyu_at_the_Golden_Disc_Awards_2019.png" alt="singing" width="100" height="100" id="smile">


<p>onmouse out and onmouseover changing images</p>

</body>
</html>
Kuo-hsuan Hsu
  • 677
  • 1
  • 6
  • 12
0

You don't need the / at the start of your path to gif.

Replace document.getElementById("smile").src = "/smiley.gif" with document.getElementById("smile").src = "smiley.gif"

Same for the sing.gif

Nikola Dim
  • 736
  • 7
  • 21
0

Instead of using javascript to change image source on mouseout and mouseover, it will be better to change image source on based on just hover.

Check this out: CSS: Change image src on img:hover

  • Hover handles both a mouseenter event and a mouseleave event.

  • Mouseover is best for situations where you only care when the mouse has crossed the border into an element and you don't really care what happens if it leaves. If you want to trigger some event on the element.