SarahG818
SarahG818

Reputation: 47

Image source change on hover not working as expected

I'm trying to create an image that plays a GIF on hover. I found some jquery on this site that supposedly works but for some reason isn't working for me. Any ideas as to why?

This is the html and javascript:

$(document).ready(function(){


//animate image on hover
    $(document).ready(function()
    {
        $("#imgAnimate").hover(
            function()
            {
                $(this).attr("src", "Videos/Mathew-Demo.gif");
            },
            function()
            {
                $(this).attr("src", "Static shots/Mathew-Demo.png");
            });
    });




});
<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" type="text/css" href="team.css">
  <script src="team.js" type="text/javascript">
  <script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>

<body>
    <img src="Static shots/Mathew-Demo.png" id="imgAnimate">


</body>

</html>

There is probably a very simple reason why not.

Upvotes: 1

Views: 57

Answers (2)

SebRut
SebRut

Reputation: 604

Your script fails because it tries to use jQuery's "$" before jQuery is loaded. you should move your script declaration to the bottom auf your body tag like this:

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="team.css">
    <script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
    <img src="Static shots/Mathew-Demo.png" id="imgAnimate">

    <script src="team.js" type="text/javascript">
</body>

Upvotes: 1

Martijn
Martijn

Reputation: 16103

You have a documentReady in a documentReady which has no use (documentReady waits until the DOM is ready, the 2nd check is double).

Also, you can use the .src property directly, resulting in the following code:

$(document).ready(function()
{
    $("#imgAnimate").hover(
        function(){
            this.src = "Videos/Mathew-Demo.gif";
        },
        function(){
            this.src = "Static shots/Mathew-Demo.png";
        }
    );
});

Apart from that, your code seems fine. Are you sure jQuery is loaded? Your snippet does not include it. Here is a snippet with working example.

Upvotes: 1

Related Questions