Reputation: 87
Hi all i am simply trying to remove this keyup event from the window and it is not working.
toggle(forceClose = false) {
const shouldClose = forceClose || this.isOpen()
const action = shouldClose ? 'remove' : 'add'
const expanded = !shouldClose
var escape = function(e) {
if (e.key === "Escape" || e.which === 27) {
console.log("Escape")
}
}
if (shouldClose && this.targetEl) {
window.removeEventListener('keyup', escape, true)
this.targetEl.classList.remove(this.options.menuActiveClass)
setTimeout(() => !this.targetEl.classList.contains(this.options.menuActiveClass) && this.targetEl.classList.remove(this.options.menuOpenClass), 300)
} else if (this.targetEl) {
window.addEventListener('keyup', escape, true)
this.targetEl.classList.add(this.options.menuOpenClass)
setTimeout(() => this.targetEl.classList.contains(this.options.menuOpenClass) && this.targetEl.classList.add(this.options.menuActiveClass), 10)
}
}
Upvotes: 0
Views: 93
Reputation: 1048
When you call removeEventListener you have to pass as function the same instance passing on addEventListener.
So in your case you have to define escape ouside toggle
Upvotes: 0
Reputation: 45106
You are creating a new escape
function on every call. So removeEventListener
will try to remove something that never been added.
Move the declaration to the outer scope
toggle(forceClose = false) {
const shouldClose = forceClose || this.isOpen()
const action = shouldClose ? 'remove' : 'add'
const expanded = !shouldClose
if (shouldClose && this.targetEl) {
window.removeEventListener('keyup', escape, true)
this.targetEl.classList.remove(this.options.menuActiveClass)
setTimeout(() => !this.targetEl.classList.contains(this.options.menuActiveClass) && this.targetEl.classList.remove(this.options.menuOpenClass), 300)
} else if (this.targetEl) {
window.addEventListener('keyup', escape, true)
this.targetEl.classList.add(this.options.menuOpenClass)
setTimeout(() => this.targetEl.classList.contains(this.options.menuOpenClass) && this.targetEl.classList.add(this.options.menuActiveClass), 10)
}
}
function escape(e) {
if (e.key === "Escape" || e.which === 27) {
console.log("Escape")
}
}
Upvotes: 1