Change image on click then back to original image on another image click/html jscript

44 Views Asked by At

First of all, I have basically no knowledge on how to write JavaScript, so my problem might be quite simple to answer, but I've done some research and I didn't find anything yet. I'd like to know how to change my image on click then back to original image when another image is clicked, not the same one.

In my research, I've found how to go from one image to another on click and I found this :

function changeImage(img){
  if(img.src=="resources/items/original_image.png"){
    img.src="resources/items/icon2blue.png";
  }else {
    img.src="resources/items/original_image.png"; 
  }
}

which works perfectly, but is not really want I want to do. And I don't know how to modify this to arrive where I want to go haha.

I found another post on the forum with the same problem but couldn't make any of the solution answered work. thanks to anybody who helps :)

1

There are 1 best solutions below

0
Izebeafe On

From how I understand the question, there are two images, and when the main/original image is clicked, that same one should be changed to another image, but when another image is clicked, then the original image should be changed from the icon2blue.png to the original image it was.

Okay assuming your first image is

<img class="first-image" src="resources/items/original_image.png" alt="first image" />

and the second one is

<img class="second-image" src="source/not/specified.png" alt="first image" />
<!-- Set the source to whatever that image is -->

Your JavaScript file will be as so:

const image1 = document.querySelector("img.first-image") // This gets the original image using it's class name
const image2 = document.querySelector("img.second-image") // Gets the second image

//then make functions for setting/reverting the image source
function revertImage(){
    image1.src = "resources/items/original_image.png" // this will set the first-image back to the original
}

function changeImage(){
    image1.src = "resources/items/icon2blue.png" // this will change the first-image to the "icon2blue.png"
}

// next, listen to when the first is clicked
image1.addEventListener("click", changeImage) // so whenever the first image is clicked, the image's source would be changed to the "icon2blue"

// when the second image is clicked
image2.addEventListener("click", revertImage) // anytime the second image is clicked, the first image's source would be changed back to the original source

Hope I answered your question. If I misunderstood something, let me know :)