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?
7 odpowiedzi
+ 2
I'd use ids for each image and put them in a div with aclass
+ 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...
+ 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
+ 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!!
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
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.
0
I would definitely try the code mentioned, thanks.