I am trying to remove an Event listener from my button after I add an event listener, most like overriding the previous code, but it isn’t working, I tried to console log, but it gives undefined, not sure why. What am I doing wrong/missing?
app.js
document.querySelector("button").addEventListener("click", function(){
document.querySelector(".dialog").style.display = "block"
setTimeout(()=>{
document.querySelector(".dialog").style.display = "none"
}, 2500)
})
document.querySelector("button").removeEventListener("click", sayHi);
function sayHi(){
console.log('hello')
}
index.html
<div class="container">
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Voluptate in illo omnis vitae molestias natus eaque necessitatibus molestiae nesciunt illum!
<button>find out more</button>
</div>
<div class="dialog" style="display: none;">
<div class="context">
<h1>Hi!</h1>
</div>
</div>
app.css
.container{
width:500px;
height: auto;
margin:0 auto;
}
button{
margin:20px auto;
display: flex;
justify-content: center;
cursor: pointer;
}
.dialog{
width: 100%;
height: 100%;
background: black;
opacity: 0.8;
position: absolute;
top:0;
left:0;
display: flex;
justify-content: center;
}
.context{
width: 400px;
height: 400px;
background: white;
margin: auto;
display: flex;
justify-content: center;
align-items: center;
}
>Solution :
You have to keep the reference to the function you want to remove like this:
function popup(){
document.querySelector(".dialog").style.display = "block"
setTimeout(()=>{
document.querySelector(".dialog").style.display = "none"
}, 2500)
}
document.querySelector("button").addEventListener("click", popup)
document.querySelector("button").removeEventListener("click", popup);
and the reason is removeEventListener needs to know exactly which function to remove from the target element events, because you can add a lot of functions to the same event, and if you want to remove one you have to say which one