0
Hey guys, I made a simple to-do app with pure HTML, CSS and JS. However after q finished the project came to me a question: I have an Eventlistener to create a:
document.querySelector('.add').addEventListener('click', () => {
const taskDiv = document.createElement('div')
const taskTitle = document.createElement('h2')
const paragraph = document.createElement('p')
const button = document.createElement('button')
const deleteBtn = document.createElement('button')
and as you can see by the last two elements created, in each task I have two buttons (the first to finish the task and the other to delete). Now to add an Eventlistener (click) to these 2 buttons, the only way q thought was to soon after generating these HTML elements by javascript, add the Eventlistener to both buttons.
button.addEventListener('click', ()=> {
numbersTasksSpan[1].textContent = --tasks.inProgress
numbersTasksSpan[0].textContent = ++tasks.completed
button.parentElement.remove()
})
deleteBtn.addEventListener('click', ()=> {
numbersTasksSpan[1].textContent = --tasks.inProgress
numbersTasksSpan[2].textContent = ++tasks.deleted
deleteBtn.parentElement.remove()
})
Note that the two Click Events above are in the same block as the Eventlistener adding to-do. In short:
EventListener para criar uma tarefa {
...
...
EventListener do botão tarefa concluida {}
EventListener do botão deletar tarefa {}
}
If I put the Eventlistener of the two buttons outside the scope of what creates a to-do, it won’t work because when the script presses the buttons they don’t even exist yet
The code worked, but I got the impression that it is not the right way to do it. There were two Eventlisteners inside an Eventlistener.
Using a framework/library would be simpler to do but I chose to do with pure js
Is there any other way to do it? Or is that way correct?
"Two Eventlisteners inside an Eventlistener" - So what? When an element X is clicked vc creates other elements A and B and each of them also needs to have their own listeners, so that’s the way to do it. It doesn’t need a framework, and there’s nothing weird about it...
– hkotsubo