I have a button that displays a custom dialogue box. If the user selects 'cancel', the dialogue box should be removed from the DOM and no further action is taken. If they click 'Start Delete', it should proceed with code.
The dialogue box shows and hides correctly, however, after I cancel and hide the dialogue box, the button no longer works to display the dialogue box again.
I have created a popup class that uses a template string to display the popup and I then inject it into the DOM. The popup takes a callback in the constructor, which I use to hide the popup.
Please see the following JS Fiddle: https://jsfiddle.net/khgriffi259/vs6r5ake/13/
class Popup {
constructor(title, message, callback) {
this.title = title;
this.message = message;
this.callback = callback;
this.container = document.querySelector('body');
this.result = '';
}
init() {
const popup = `
<div class="popup-wrapper">
<div class="popup bg-white p-1">
<div class="popup-close">X</div>
<div class="popup-content ">
<h2 class="">${this.title}</h2>
<p class="p-1 my-2">${this.message}</p>
<div class="dialogue_buttons my-1">
<button class="btn popup-no" >Cancel</button>
<button class="btn btn-danger my-1 popup-yes" >Start Delete</button>
</div>
</div>
</div>
</div>
`;
this.container.innerHTML += popup;
this.container.querySelector('.popup-no').addEventListener('click', () => this.cancelListener());
this.container.querySelector('.popup-yes').addEventListener('click', () => this.startListener());
}
cancelListener() {
this.result = false;
this.callback();
// if (this.callback !== undefined) {
// this.callback(this.result);
// }
}
startListener() {
this.result = true;
if (this.callback !== undefined) {
this.callback();
}
}
getResult() {
console.log(this.result) ;
return this.result;
}
}
//end of Popup Class
const button = document.querySelector('button');
button.addEventListener('click', e => {
if (e.target.tagName === 'BUTTON') {
const confirmDelete = new Popup(
'Delete',
'This will permanently delete this experience record.',
()=>{
console.log('hello');
let elem = document.querySelector('.popup-wrapper');
elem.parentNode.removeChild(elem);
}
);
confirmDelete.init();
}
})
<button>
click me
</button>
I expect the popup to hide and for the button to be functional to generate a new Popup if user clicks the button again.