0

I'm following a tutorial in the internet to learn some basic Javascript. One of the steps is to have an image change to another one once the user clicks over it, however, it is not working. I've found some tutorials during my research, but all of them include functions that I have yet to learn, so I would like to stick to the tutorial as much as possible.

Here's the JS script:

var myImage = document.querySelector('img');
myImage.onClick = function() {
    var mySrc = myImage.getAttribute('src');
    if(mySrc === 'images/1.png') {
        myImage.setAttribute ('src', 'images/2.png');
    } else {
        myImage.setAttribute ('src', 'images/1.png');
    }
}

Here's the link for the tutorial I'm using: https://developer.mozilla.org/en-US/Learn/Getting_started_with_the_web/JavaScript_basics

And here's the project's Github link: https://github.com/Pedro12909/test

1

2 Answers 2

1

The issue is .onClick is not defined. Use .onclick with lowercase "c"

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the help, it took me 4 hours to figure this out!!!! i love you forever <3 brb, going to smash my head against a wall now....
0

If you are using query selector,then you will have to bind the click event for all images in the page. Query selector will return a list of HTML elements, and you will have to iterate through them. Try adding an id to the img tag ,say imageId and do the following modification.

var myImage = document.getElementById('imageId');
myImage.onclick = function() {
	var mySrc = myImage.getAttribute('src');
	if(mySrc === 'images/1.png') {
		myImage.setAttribute ('src', 'images/2.png');
	} else {
		myImage.setAttribute ('src', 'images/1.png');
	}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.