javascriptonmouseoveronmouseout

JavaScript changing images with onmouseover and onmouseout


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>

Solution

  • 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>