Search code examples
jqueryhtmlreferenceerror

Uncaught ReferenceError: img is not defined


So I am new to JQuery and HTML and I got the Uncaught ReferenceError: img is not defined error in the console, but I don't know what that means or how to fix it.... My project should be a slide show so when you click on the next button it goes to the next picture. I haven't added in all of the photos yet because I wanted to get this working first, but there will be 4. Also, I'm use the editor on Khan Academy, so if some of the variables are weird (such as var) that's why.

Here is my body and script code and thanks for the help!

<body>

<br>
<img>
<button type="button" id="next">Next ➡</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> //access to jQuery library
<script>
var photo=function(nums){
    console.log("nums "+nums);//checking to see if the right number was received from the function
    if (nums===1){
        $("img")//I think the problem is here
            .css("src","https://www.kasandbox.org/programming-images/food/mushroom.png")//photo on khan academy
            .css("width","400")
            .css("alt","Mushrooms");
    } else if (nums===2){
        $("img")
            .css("src","https://www.kasandbox.org/programming-images/food/coffee-beans.png") //photo on khan academy
            .css("width","400")
            .css("alt","Coffee Beans");
    }  
    $("img").slideDown(1000);
}

$("img").hide();

$("#next").on("click", function() {
        var num = 0;
        if(num < 4){
            num++;
        }else{
            num = 1;
        }
        console.log("num "+num);//checking to see if the right number was sent to the function
        photo(num);
    });


</script>
</body>

Solution

  • img needs to be a string

    use $("img")

    the way you have it written javascript is looking for an object called img which you never define.. alternatively you could define img like this var img = "img"