I have an focus and keydown events. Everytime the input element is out of focus or an enter key is pressed, I update the page to reflect the changes.
The Render class rerenders the currently selected page.
The issue here is that when I update the page with the enter key, both the focusout
and kedown
events are fired. This code seems to work only if I give the event's callback a timeout
.
The question is, is it possible to sovle this "event colission" without setTimeout
and why does that happen?
// Page content class
const descriptionInput = document.createElement('textarea');
const handleDescription = function(e){
if( (e.key === "Enter" && !e.shiftKey) ||
(e.type === "focusout")
){
task.description = this.value;
storage.updateTask(task.id, task);
(new Render).refreshPage()
}
}
descriptionInput.addEventListener('keydown', handleDescription)
descriptionInput.addEventListener('focusout', handleDescription)
// Render class
renderPage(contentFunction){
const pastContent = document.querySelector('.content');
if(pastContent) this.pageContainer.removeChild(pastContent);
this.pageContainer.appendChild(contentFunction());
}
refreshPage(){
const currentPage = document.querySelector('.sidebar li[selected]');
switch (currentPage.getAttribute('name')) {
case 'Active Task':
this.renderPage(activeTasks);
break;
case 'Complete Task':
this.renderPage(completeTask);
break;
}
}
// No error snippit
if( (e.key === "Enter" && !e.shiftKey) ||
(e.type === "focusout")
){
setTimeout(() => {
task.description = this.value;
storage.updateTask(task.id, task);
(new Render).refreshPage()
}, 100)
}