user2758781
user2758781

Reputation:

JavaScript Event is not working with getElementById

I have a problem with JS Events. I placed an image on my website and with the help of JS when one would click the image, the src attribute would be set to find another image. But nothing happens!

CODE

<img id="img" src="Login_img1.jpg" width="425" height="219" alt="Hey" onclick="img()">

Now the JS:

function img(){document.getElementById("img").src = "Login_img2.jpg"}

Upvotes: 0

Views: 153

Answers (5)

Alex W
Alex W

Reputation: 38193

Just use unobtrusive JavaScript, and ditch the HTML onclick attribute:

var img = document.getElementById('img');
img.onclick = function(){
    img.src = "Login_img2.jpg";
};

Upvotes: 1

user2672373
user2672373

Reputation:

You have already got solution to your question. Just want to point out that you may do it using event listeners too.

var oImg = document.getElementById('myImg');
oImg.addEventListener('click', function() {
    this.setAttribute('src', 'Login_img2.jpg');
}, false);

Upvotes: 0

jcreamer898
jcreamer898

Reputation: 8189

It could be do to the fact that you named both your function img and the id of your element img.

Browsers will actually use ID's as global variables. So, simply by creating an element with an id of img you've essentially created window.img.

It'd be bettr to rename your function to something like swapImg and use this and the JavaScript onclick method instead of having your onclick in the markup as well as wrapping your code in an IIFE to avoid leaking variables into the global window object...

(function() {
    document.getElementById('img').onclick = swapImage;

    function swapImage() {
        this.src = 'Login_img2.jpg';
    };
})();

Upvotes: 0

letiagoalves
letiagoalves

Reputation: 11302

This could simple be done using this keyword removing the unnecessary search for the element.

<img id="img" src="Login_img1.jpg" width="425" height="219" alt="Hey" onclick="change_img(this)">

function change_img(img){
   img.src = "Login_img2.jpg";
}

Upvotes: 0

j08691
j08691

Reputation: 207901

Don't name your function img(). It works fine when you use something that's not equivalent to a global object.

Upvotes: 3

Related Questions