0

How would you toggle between 2 images using plain javascript?

Im trying to write a code from scratch, where you would toggle between an image and another image.Should I use a class attribute or id attribute. Any suggestions is appreciated?

11th Jul 2024, 4:21 AM
Akash Mahato
Akash Mahato - avatar
7 odpowiedzi
+ 2
I'd use ids for each image and put them in a div with aclass
11th Jul 2024, 6:56 AM
Ausgrindtube
Ausgrindtube - avatar
+ 1
When you say "toggle between 2 images"; did you mean to toggle/change the content of an <img> element, or toggle visibility of two <img> elements? or was it a totally different thing you're doing here? You mentioned plain Javascript, id and class attribute. What was your idea of their use in achieving the goal? Just asking for more clarity...
11th Jul 2024, 7:22 AM
Ipang
+ 1
Use an ID for styling a single element. Use a class when styling multiple elements with the same style. So also use ID in Javascript to target indiviual objects
11th Jul 2024, 10:01 PM
Chris Coder
Chris Coder - avatar
+ 1
<!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <h1>Toggle image</h1> <img src="https://images.app.goo.gl/x6QEbjQ6pHeYxABF7" id="test" onclick="change();"> <script> function change() { var imgElement = document.getElementById('test'); if (imgElement.src.includes("x6QEbjQ6pHeYxABF7")) { imgElement.src = "https://images.app.goo.gl/YtDF7v7PWsMujxU37"; } else { imgElement.src = "https://images.app.goo.gl/x6QEbjQ6pHeYxABF7"; } } </script> </body> </html> I hope that referring to this code helps you out!!
12th Jul 2024, 7:08 AM
Meenal Shelar
Meenal Shelar - avatar
0
So what I'm trying to do is this, i have 2 images in inline or that is how they show up when I wrap them inside a border container. Now what I want is that when you click on image1 image2 should display and vice versa, hiding imaging one at the same time and displaying image2
11th Jul 2024, 9:22 AM
Akash Mahato
Akash Mahato - avatar
0
When you say "toggle between 2 images"; did you mean to toggle/change the content of an <img> element, or toggle visibility of two <img> elements? or was it a totally different thing you're doing here? You mentioned plain Javascript, id and class attribute. What was your idea of their use in achieving the goal? Just asking for more clarity... @ the former one is my question.
11th Jul 2024, 9:23 AM
Akash Mahato
Akash Mahato - avatar
0
I would definitely try the code mentioned, thanks.
23rd Jul 2024, 12:19 PM
Akash Mahato
Akash Mahato - avatar