On click doesn't work

Hi guys, I’m trying to make an image changer using Javascript
and there’s always that error in the console

main.js:50 Uncaught ReferenceError: i is not defined at HTMLImageElement.myImage.onclick (main.js:50)

Here’s my HTML code

<!DOCTYPE html>
<html>
    <head>

    </head>
    <body>
        <header>
            <h1>
                hello world
            </h1>
    <img src="1.jpg" alt="myimage"  >
        </header>
        <script src="main.js"> 
        
        </script>
    </body>
</html>

and this is Javascript code

let myImage= document.querySelector('img');
myImage.onclick= function ()
{
    let mysrc= myImage.getAttribute('src');
    if(mysrc===i.jpg)
    {
        myImage.setAttribute('src','2.jpg');
    }
    else{
        myImage.setAttribute('src','1.jpg');
    }
}

Hi Ola,

It looks like the copy paste of your JS code didn’t work, can you try it again please :slight_smile: ?

oh I’m sorry I’ll try posting it again

I’ve updated it just now …

No problem ;),

Is that all your code ?
I am beginner but for the little I know the problem come from this part :

if(mysrc===i.jpg)

What is i.jpg ? I guess you wanted yo use a counter that become “1.jpg”, “2.jpg” etc. But none is declared. Furthermore I am not sure il would work like this. Maybe you should try to put “.jpg” between quote marks and concatenate it with i.

1 Like

Back tracking to what Meditsh stated, JS is trying to look for the property i.jpg, you would need to wrap it in quotes if you are trying to compare against a string, or concatenate the i, if it’s a counter to the string “jpg”. If it’s the second issue, I would recommend using template string literals instead, as it’s easier to read and understand.

2 Likes

Wow I didn’t even notice that I wrote “i” instead of 1 …thanks alot!

2 Likes