I have some trouble with my javascript
I have two images. When I wanna click randomly an image, it will be replaced with the image in the JS. if I click on the rest image, it also will be replaced like the previous image but the previous image will return to the original image. How can I do that??
Thanks a lot.
This is my code. Sorry for my bad English skills
function openPresent(event){
event.target.src ='https://i2.wp.com/gsviec.com/wp-content/uploads/2020/02/coder-dev-1.jpeg?fit=900%2C500&ssl=1';
}
const image = document.querySelectorAll('img');
let i;
for(i=0;i<image.length;i++){
image[i].addEventListener('click',openPresent);
}
<!DOCTYPE html>
<html>
<link rel="stylesheet" type="text/css" href="style.css">
<head>
<style>
</style>
<script src='script.js'defer></script>
</head>
<body>
<h1>Click for a present:</h1>
<img src=https://timviec365.com/pictures/images/coder-la-gi-3.jpg>
<h1>Hello World</h1>
<img src="https://img.timviec.com.vn/2020/10/coder-la-gi-2.jpg">
</body>
You can save your original image src in an array. When changing the src on click, revert all the srcs to original and just change the one for target.
Have a look at this:
function openPresent(event){
const image = document.querySelectorAll('img');
for(let i=0;i<image.length;i++){
image[i].src= originalImagesSrcArray[i];
}
event.target.src ='https://i2.wp.com/gsviec.com/wp-content/uploads/2020/02/coder-dev-1.jpeg?fit=900%2C500&ssl=1';
}
const image = document.querySelectorAll('img');
let i;
let originalImagesSrcArray = [];
for(i=0;i<image.length;i++){
originalImagesSrcArray.push(image[i].getAttribute('src')); image[i].addEventListener('click',openPresent);
}
console.log(originalImagesSrcArray);
<!DOCTYPE html>
<html>
<link rel="stylesheet" type="text/css" href="style.css">
<head>
<style>
</style>
<script src='script.js'defer></script>
</head>
<body>
<h1>Click for a present:</h1>
<img src="https://timviec365.com/pictures/images/coder-la-gi-3.jpg">
<h1>Hello World</h1>
<img src="https://img.timviec.com.vn/2020/10/coder-la-gi-2.jpg">
</body>