I am trying to create an onclick event for changing an image from an array of images. With my current HTML I am able to render the first image. After that I am unable to change to the next image in the array.
class Change {
constructor(clickPlant) {
this.clickPlant = clickPlant;
this.image = document.createElement("img");
}
clickImage = function () {
main.append(this.image);
this.image.addEventListener("click", function () {
if (something) {
something;
return something;
}
});
};
}
arrayOfPlant = [];
let flower = new Change(
"images/flower/flower0.png",
"images/flower/flower1.png",
"images/flower/flower2.png",
);
arrayOfPlant.push(flower);
console.log(arrayOfPlant);
flower.clickImage();
for (let i = 0; i < plant.length; i ) {}
...
I made some updates to my array and classes. I hope this helps make sense of what I am trying to do. I still cant figure out how to change the image from the array using a click event listener though.
...
<body>
<main><div id="images">
<img src="images\flower\flower0.png" alt="" id="clickImage">
<div ></div>
<a href="javascript:clickImage('clickImage')"><img src="images\flower\flower0.png"></a></main>
<script src="code.js"></script>
</body>
...
CodePudding user response:
- Use as your first class argument the desired Element to append your image to:
parent
- Use the Rest Parameters syntax
...
to get the array of paths, sources to your images - Assign the click handler only once inside your Class, not outside
- Use the Reminder (Modulo) Operator
%
to loop yourthis.current
index - Use
.src =
to change the src attribute of your IMG Element to another image source.
class Change {
constructor(parent, ...sources) {
this.image = document.createElement("img");
this.parent = parent; // Where to append your IMG Element
this.sources = sources; // Sources paths (array)
this.tot = sources.length; // How many images do we have
this.current = 0; // Start at index 0
// Init
this.image.src = this.sources[this.current]; // Set source
this.parent.append(this.image);
this.image.addEventListener("click", () => this.nextImage());
}
nextImage() {
this.current = 1; // Increment counter
this.current %= this.tot; // Loop from beginning
this.image.src = this.sources[this.current]; // Set source
}
}
const flower = new Change(
document.querySelector("#flowers"),
"https://i.stack.imgur.com/2T3pZ.png",
"https://i.stack.imgur.com/F2FgF.png",
"https://i.stack.imgur.com/xRth8.png",
);
Click the image:
<div id="flowers"></div>
CodePudding user response:
You have to declare the function for nextImage
.
The href
on the link wrapped over the image is attempting to call a function called nextImage
.