1

I am trying to change the image by clicking on it. I have written the codes and it's not working.

<div class="img fadeIn" >
        <img src="logo.png" height="90px" width="320px" onclick="change()" id="koo" />
    </div>

JavaScript code:

function change() {
var mySrc = this.getAttribute('src');
    if( mySrc == 'logo.png' ){
        this.setAttribute('src','logo1.png');
        } else {
        this.setAttribute('src','logo.png');
        }
    }
4
  • Does your javascript console report any errors? Commented Jul 4, 2018 at 10:00
  • This might prove to be helpful Commented Jul 4, 2018 at 10:00
  • @ZombieChowder It would be better if we make changes and debug the current code instead of changing the whole logic Commented Jul 4, 2018 at 10:03
  • @Arex I'm just sending him a link to see how it's done and amend the code to his own. The whole teach a man to fish, give him a fish thing.. Commented Jul 4, 2018 at 10:04

3 Answers 3

1

You have to put the element as an argument to the function. I have attached the working code.

function change(t) {
var mySrc = t.getAttribute('src');
    if( mySrc == 'logo.png' ){
        t.setAttribute('src','logo1.png');
        t.setAttribute('alt','logo1');
        } else {
        t.setAttribute('src','logo.png');
        t.setAttribute('alt','logo');
        }
    }
<div class="img fadeIn" >
        <img src="logo.png" height="90px" width="320px" onclick="change(this)" id="koo" alt="logo"/>
    </div>

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

2 Comments

Do tell me if any more help is needed
@RA'sal Glad to help :)
0

There is also a way to do this. Please refer to the code

<div class="img fadeIn">
     <img src="logo.png" height="90px" width="320px" onclick="change()" id="koo" />
</div>

function change() {
    var imgTag = event.target;
    var mySrc = imgTag.getAttribute('src');
    if( mySrc == 'logo.png' ){
        imgTag.setAttribute('src','logo1.png');
    } else {
        imgTag.setAttribute('src','logo.png');
    }
}

Comments

0

Try This!

var ele = document.getElementById("koo");
ele.addEventListener('click',function(){
var src = (ele.getAttribute('src') == "logo.png")?"logo1.png":"logo.png";
ele.setAttribute('src',src);
})
<div class="img fadeIn" >
      <img src="logo.png" height="90px" width="320px" id="koo" />
</div>

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.