I am currently working on creating a custom confirmation function from scratch, without using any libraries. This function is designed to display a modal window with buttons that will return either true
or false
.
if(getConfirmation) {
do something
} else {
do something
}
Most of the implementation is complete except for handling button interactions. The issue I am facing is that I am unable to halt the code execution in the same manner as the default confirm
function does. Upon clicking the button labeled Click me
at line 56, I receive either undefined
or Cancel
instead of properly executing the getConfirmation
function.
const button = document.querySelector('#abc')
button.addEventListener('click', (e) => {
// usage
if(getConfirmation(options)) {
console.log('Ok')
} else {
console.log('Cancel')
}
})
The current structure of the code seems fine, but I suspect the issue lies in how I am detecting button clicks.
function getConfirmation(options) {
const element = createElement('confirm_window')
element.insertAdjacentHTML('afterbegin', getTemplate(options))
document.body.appendChild(element)
element.querySelectorAll('button').forEach(button => {
button.addEventListener('click', function(e) {
const result = options.buttons.find(b => b.name === e.target.name).result
document.body.removeChild(element)
return result
})
})
}
My question is: How can I ensure that the function waits until any button click occurs (either Confirm
or Cancel
)?
For a demonstration, you can view the code here: https://codepen.io/hamper_/pen/eYzNXqN?editors=1010