I would like to attach an event listener (that calls a function) to a button that is not yet present in the DOM. I don't want to use inline-call in the HTML how can I do it?
So far i could achieve what I wanted by creating a global event listener
that checks if the element clicked has a specific Id. But I found this solution to be dirty and not optimal.
const messageForm = document.querySelector(#message-form)
const messageTextarea = document.querySelector(#message-textarea);
const messageList = document.querySelector(#message-list);
const messageEmpty = document.querySelector(#message-empty);
let messageNumber = 0;
const messageFormatted = messageText => {
return `
<li class=message-item>
<img class=message-avatar src=./icons/boy.png alt=Username>
<article class=message-content>
<p class=author>Ernesto Campese</p>
<p class=message>${messageText}</p>
<p class=datetime>A moment ago</p>
</article>
<div class=message-actions>
<img id=message-edit class=action-button src=./icons/edit.png alt= width=22 height=22>
<img id=message-delete class=action-button src=./icons/delete.png alt= width=22 height=22>
</div>
</li>
`;
}
document.addEventListener(click, (e) => {
if (e.target.id === message-delete) {
e.target.parentNode.parentNode.remove();
messageNumber--;
messageEmptyCheck();
}
})
messageForm.addEventListener(submit, (e) => {
e.preventDefault();
if (messageTextarea.value !== ) {
messageList.insertAdjacentHTML(beforeend, messageFormatted(messageTextarea.value));
messageTextarea.value = null;
messageTextarea.focus();
messageNumber++;
messageEmptyCheck();
}
});
As you can see in the code, inside the <li>
that I'm creating there are two IMG, one is for deleting and the other for editing. I want to add an event listener to the delete IMG, so when the user clicks it, the li gets eliminated.
The problem is that I cannot create any function if the element does not exist yet. I would love to do something like:
const messageDeleteButton = document.querySelector(#message-delete);
messageDeleteButton.addEventListener(click, (e) => {
e.parentNode.parentNode.remove();
}
})
Hope I was clear enough, thank you guys!