I have created a function add element to click event listener. It is supposed to be change img src attribute but at least one element doesnt change src attribute when I add a few new items
the code is like that:
function updateCheckButtons(){
let checkButtons= document.querySelectorAll(".uncheck");
checkButtons.forEach(chk=>{
chk.addEventListener("click",function(){
let src=chk.getAttribute("src");
if(src.endsWith("unchecked.png")){
chk.setAttribute("src","images/checked.png")
}
else {
chk.setAttribute("src","images/unchecked.png")
}
})
})
}
2
Answers
I solved my problem. Thank you. Instead of calling the addEventFunction for every item when adding them dynamically, which handles both old and new items, I created a function that addresses and adds an event handler only for the last item. This approach resolved the issue. that is the working code
If you want to toggle an image from checked/unchecked, I would first name my functions more meaningfully.
Now, I would store the images in a state array. The unchecked state should be at index 0, and the checked should be at index 1. You can now use modular arithmetic to cycle through the images.
Now, what I would recommend is that you use data attributes + CSS to style the checkboxes. The checkbox should be represented as a
<span>
or<div>
, and the image should be a CSS background image.The added benefits of data attributes are: