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

j08691
  • 204,283
  • 31
  • 260
  • 272

2 Answers2

1

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

guest271314
  • 1
  • 15
  • 104
  • 177
  • 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.... – Pedro Portela Jul 12 '16 at 02:29
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');
 }
}