I created this test code to test the problem I am facing, here when we click on any of the buttons, it opens a test drawer, and inside the test drawer when we click on the text, it console log the text, but after that when we close the drawer with the close button inside the drawer, and opens a new drawer, the console log is firing 2 times and the number keeps on increasing the times we open and reopen the drawer, why is this happening? how to solve it?
const test_modal = document.querySelector('.test-modal');
document.addEventListener('click', (e) => {
if(e.target.classList.contains('btn')) {
e.preventDefault();
const value = e.target.closest('.btn').getAttribute("data-name");
showmodal(value);
}
})
function showmodal(value) {
test_modal.innerHTML = `
<div class="inner-test"><h3 class="heading-test">${value}</h3><button class="closeme">Close</button></div>
`;
document.addEventListener('click', (e) => {
if(e.target.classList.contains('heading-test')) {
console.log(e.target);
}
})
}
document.addEventListener('click', (e) => {
if(e.target.classList.contains('closeme')) {
test_modal.innerHTML = ``;
}
})
.inner-test {
background: tomato;
width: 80px;
height: 80px;
}
<button data-name="first" class="btn">
I am First
</button>
<button data-name="second" class="btn">
I am Second
</button>
<button data-name="third" class="btn">
I am Third
</button>
<div class="test-modal">
</div>
You need to remove click event listener when you close the modal.
const test_modal = document.querySelector('.test-modal');
document.addEventListener('click', (e) => {
if(e.target.classList.contains('btn')) {
e.preventDefault();
const value = e.target.closest('.btn').getAttribute("data-name");
showmodal(value);
}
})
let clickHandler;
function showmodal(value) {
test_modal.innerHTML = `
<div class="inner-test"><h3 class="heading-test">${value}</h3><button class="closeme">Close</button></div>
`;
clickHandler = (e) => {
if(e.target.classList.contains('heading-test')) {
console.log(e.target);
}
}
document.addEventListener('click',
clickHandler
)
}
document.addEventListener('click', (e) => {
if(e.target.classList.contains('closeme')) {
document.removeEventListener('click', clickHandler)
test_modal.innerHTML = ``;
}
})
.inner-test {
background: tomato;
width: 80px;
height: 80px;
}
<button data-name="first" class="btn">
I am First
</button>
<button data-name="second" class="btn">
I am Second
</button>
<button data-name="third" class="btn">
I am Third
</button>
<div class="test-modal">
</div>