I have two addEventListener, the one is to change the text color and the other one to change the circle color.
Condition 1: When I clicked the circle, both of text and circle color was changed.
Condition 2: The problem was when I clicked the text, its color was changed, but the circle didn't change.
So can I merge it into just only one addEventListener at the circle? and disable click for the text? Or can I make the text work like I clicked the circle?
Github Link
Preview
let lists = document.querySelectorAll(".list-item");
let circles = document.querySelectorAll(".fa-circle");
// Click the text
Array.from(lists).forEach((list) => {
list.addEventListener("click", () => {
list.classList.add("done");
});
});
// Click the circle
Array.from(circles).forEach((circle) => {
circle.addEventListener("click", () => {
circle.classList.remove("fa-regular");
circle.classList.add("fa-solid", "fa-circle-check");
});
});
Depends on what you want. By the way, what does your DOM tree look like? is .list-item a parent of/ or a sibling to '.fa-circle'?. If you want to dispatch the event once the user clicks anywhere on a list item. Then you can use the parent, like this:
const listParents = document.querySelectorAll('.list-parent')
function handleItemClick(event) {
const listParent = event.target
const listText = listParent.querySelector('.list-item')
const listCircle = listParent.querySelector('.list-circle')
listText.classList.toggle('done')
listCircle.classList.toggle('fa-circle')
listCircle.classList.toggle('fa-regular')
listCircle.classList.toggle('fa-circle-check')
listCircle.classList.toggle('fa-solid')
l
}
Array.from(listParents).forEach(listParent => {
listParent.addEventListener('click', handleItemClick)
})