camila camila - 2 months ago 13
HTML Question

Stop gif on mover hover does not work

I want to show gif first and than when mouse hover on the gif it shows different jpg picture so that it looks like stop.
I tried this code but it didn't work.
I would like to know which part is need to be fixed.

<html>
<script>
$(document).ready(function()
{
$("#imgDino").hover(
function()
{
$(this).attr("src",
"http://s2.favim.com/610/150619/airplane-fly-landscape-plane-Favim.com-2831842.jpg");
},
function()
{
$(this).attr("src", "https://66.media.tumblr.com/233306b207ff895cc591ee86684fd792/tumblr_mze5yi7uwQ1sqqsygo1_400.gif");
}
);
});
</script>
<body>
<img id="imgDino" src="https://66.media.tumblr.com/233306b207ff895cc591ee86684fd792/tumblr_mze5yi7uwQ1sqqsygo1_400.gif" />

</body>
</html>

Answer

There are two problems here with your code:

  1. You are not loading jQuery - so you can't use it. And the console (F12) throws an error for that: Uncaught ReferenceError: $ is not defined

  2. You are registering the javascript-event before the dom-element is available

So a working solution for your scenario would be:

<html>

  <head>

  </head>

  <body>
    <img id="imgDino" src="https://66.media.tumblr.com/233306b207ff895cc591ee86684fd792/tumblr_mze5yi7uwQ1sqqsygo1_400.gif" />

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <script>
      $(document).ready(function() {
        $("#imgDino").hover(
          function() {
            $(this).attr("src",
              "http://s2.favim.com/610/150619/airplane-fly-landscape-plane-Favim.com-2831842.jpg");
          },
          function() {
            $(this).attr("src", "https://66.media.tumblr.com/233306b207ff895cc591ee86684fd792/tumblr_mze5yi7uwQ1sqqsygo1_400.gif");
          }
        );
      });

    </script>
  </body>

</html>