I need to change an image that I have in multiple elements by just clicking on one of the images.
I am very new to coding and am trying to make a code in which selecting/clicking one image changes every image on the screen with the same name/id/class (I'm not sure which will work best or at all).
HTML:
<button onclick="changeImage()"><img src="images/bicycle.jpg" id="bicycle"></button>
<button onclick="changeImage()"><img src="images/bicycle.jpg" id="bicycle"></button>
<button onclick="changeImage()"><img src="images/bicycle.jpg" id="bicycle"></button>
JS:
function changeImage(){
var img = document.getElementById('bicycle');
img.src = 'images/car.jpg'
}
Each button has the same image inside of it and when I click one button I would like for the rest of the images in every button to change as well. I realized that when I click any of the buttons only the image in the first button changes. I read somewhere that it's normal for that to happen because it stops at the first instance of that id that it finds.
CodePudding user response:
you can't do it in that way because id must be unique, so document.getElementById will always get only the first reference.
You should find elements using the className:
var elements = document.getElementsByClassName("bicycle");
for(var i = 0; i < elements.length; i ) {
elements[i].src = 'images/car.jpg'
}
Let me know if it works.
CodePudding user response:
ID should be unique and never used more than one ID in page. document.getElementById('bicycle') return the very first matches in your code, and you are able to change very first image.
use alternate method to get elements like ( document.querySelectorAll(), Document.getElementsByClassName() ). these methods return all matching elements in the form of array. so you can loop of array to change attribute on elements.
function changeImage(e) {
let current_image_src = e.target.currentSrc;
document.querySelectorAll('.bicycle').forEach((element => {
element.src = current_image_src;
}))
}
img {
width: 150px;
cursor: pointer;
}
<img
onClick="changeImage(event)"
src="https://media.gettyimages.com/id/477445662/photo/professional-road-cyclist.jpg?s=612x612&w=gi&k=20&c=Mx-v3lSwNYMqQKfUhr_w22WUdXK3aDZqxhsHZEafok0="
/>
<img
onClick="changeImage(event)"
src="https://agavept.com/wp-content/uploads/2017/10/iStock-614649230-1024x645.jpg"
>
<img
onClick="changeImage(event)"
src="http://lemonbin.com/wp-content/uploads/2020/06/cyclist-june172020-min.jpg"
/>
CodePudding user response:
So as the first commentor said, you can't do that by ID as IDs need to be unique, so make it a class. Here is what I have come up with:
HTML:
const image = document.querySelectorAll(".element");
image.forEach((item) => {
item.addEventListener("click", function (){
for (let i = 0; i < image.length; i ) {
image[i].src = "https://picsum.photos/200";
}
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<img src="https://www.cdc.gov/healthypets/images/pets/cute-dog-headshot.jpg?_=42445" alt="Random Picture" />
<img src="https://www.cdc.gov/healthypets/images/pets/cute-dog-headshot.jpg?_=42445" alt="Random Picture" />
<img src="https://www.cdc.gov/healthypets/images/pets/cute-dog-headshot.jpg?_=42445" alt="Random Picture" />
<script src="index.js" text="text/javascript"></script>
</body>
</html>
Essentially what this is doing is declaring a const
that is the NodeList (essentially an Array for our purposes here) of my elements with the class element (so my 3 elements).
From here image.forEach((item) => {
is going through my NodeList(array) and for each item (so each image) we're adding an event listener of "click". When the click happens an anonymous function is called. This anonymous function is a for loop that will go through each image and change its "src" attribute to that picsum link. (picsum is a site that generates random images).
Whipped this up in a few minutes so it only works once, but this should hopefully get you on the right path :)
Happy coding!