AndrewLeonardi
AndrewLeonardi

Reputation: 3512

Using a click event how do I change an image?

Goal: When clicking the red square the blue square should turn red.

I'm trying to figure out how to make a copy of an image when a user clicks something. When the user clicks an image I need to generate that same image somewhere else. Currently this is my code which is not working to accomplish my goal. (Also fine with using Jquery)

HTML

<a href="#" onClick="changeImage()"> <img id="myImage" src="Images/red.jpg"></a>
<img id="new" src="Images/blue.png">

Javascript:

function changeImage(){
    if(document.getElementById('myImage').src == "Images/red.jpg"){
     document.getElementById('new').src == 'Images/red.jpg';
    }
}

Upvotes: 1

Views: 70

Answers (2)

Adraxas Nazaron
Adraxas Nazaron

Reputation: 60

This should work.

HTML

<img id="myImage" src="http://placehold.it/150">
<img id="new" src="http://placehold.it/200">

JS

$(function(){
  $("#myImage").click(function() {
    $("#new").attr("src","http://placehold.it/150")
  });
});

Upvotes: 1

Ali Mamedov
Ali Mamedov

Reputation: 5256

Please correct your code:

function changeImage() {
  var imgSrc = 'http://placehold.it/150';

  if (document.getElementById('myImage').src === imgSrc) {
    document.getElementById('new').src = imgSrc;
  }
}
<a href="#" onClick="changeImage()">
  <img id="myImage" src="http://placehold.it/150"></a>
<img id="new" src="http://placehold.it/200">

Use one "=" to set images's src.

Upvotes: 3

Related Questions