This post has been de-listed
It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.
Hey so there's a project I'm working on where I have to change the button's image on each click, changing 2 more times before it stops. At first I thought I would use a for loop to iterate it on each click but was having trouble binding it within the class. I decided to go with a few if statements as part of the eventListener but still having an issue binding it. The logic of it makes sense to me but I'm not sure how to bind it to the class.
I hope my code copy and pasted correctly.
let flowerButton = document.createElement("button");
flowerButton.setAttribute("id", "Flower Button");
document.body.appendChild(flowerButton);
flowerButton.innerHTML = "<img src = ./images/flower/flower0.png>";
class Flower {
constructor() {
this.flowerArray = [
"./images/flower/flower0.png",
"./images/flower/flower1.png",
"./images/flower/flower2.png",
];
}
flowerImageChange() {
flowerButton.addEventListener("click", function(){
if ((flowerButton.innerHTML = "<img src = ./images/flower/flower0.png>")) {
flowerButton.innerHTML = "<img src = ./images/flower/flower1.png>";
}
else if ((flowerButton.innerHTML = "<img src = ./images/flower/flower1.png>")) {
flowerButton.innerHTML = "<img src = ./images/flower/flower2.png>";
}
});
}.bind(flowerImageChange);
}
This is the code with the for loop if it helps but I think my main issue is figuring out how to bind it.
let flowerButton = document.createElement("button");
flowerButton.setAttribute("id", "Flower Button");
document.body.appendChild(flowerButton);
flowerButton.innerHTML = "<img src = ./images/flower/flower0.png>";
class Flower {
constructor() {
this.flowerArray = [
"./images/flower/flower0.png",
"./images/flower/flower1.png",
"./images/flower/flower2.png",
];
}
flowerImageLoop() {
for (let i = 0; i < this.flowerArray.length; i ) {
flowerButton.innerHTML = `<img src = ${this.flowerArray[i]}>`;
}
}
changeButtonImage() {
flowerButton.addEventListener("click", flowerImageLoop);
}
}
Subreddit
Post Details
- Posted
- 3 years ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/learnprogra...