I would like to simply delete an HTML element via JavaScript when it is clicked and after the user has provided confirmation.
After the click but before the confirmation, I want the element to be highlighted (have a different border color). However, in the code below, the confirmation is happening before the border color changes.
css:
.test-box {
border: 2px solid black;
height: 200px;
width: 200px;
cursor: pointer;
}
js:
document.addEventListener('DOMContentLoaded', () => {
const testBox = document.createElement('div')
testBox.className = "test-box"
document.body.append(testBox)
// Remove testBox when clicked
testBox.addEventListener('click', () => {
// Highlight testBox to be deleted
testBox.style.border = "2px solid yellow"
// Confirm deletion
const confirmation = confirm("Delete testBox?")
if (confirmation) {
testBox.remove()
} else {
// Remove highlight
testBox.style.border = "2px solid black"
}
})
})
The only way I can get it to work as desired is by adding a 1ms timeout to the confirmation, like this:
document.addEventListener('DOMContentLoaded', () => {
const testBox = document.createElement('div')
testBox.className = "test-box"
document.body.append(testBox)
// Remove testBox when clicked
testBox.addEventListener('click', () => {
// Highlight testBox to be deleted
testBox.style.border = "2px solid yellow"
// Delay confirmation so that highlight will happen before confirmation
setTimeout(() => {
// Confirm deletion
const confirmation = confirm("Delete testBox?")
if (confirmation) {
testBox.remove()
} else {
// Remove highlight
testBox.style.border = "2px solid black"
}
}, 1)
})
})
Is this the best way around this? I want to understand what is happening.