1

I'm trying to remove an event listener that was created inside of a function, but for some reason, it isn't working. It works fine if I take it out of the function. Example below:

<body>
<div id='myDiv'></div>
<button type='submit' onclick='rel()'>RemoveEventListener</button>

<script>
function Mouse() {
    myDiv.addEventListener('click', cK);
    function cK() {
        alert('You've clicked on myDiv!');
    }
}
function rel() {
    myDiv.removeEventListener('click', cK);
}
Mouse();
</script>
</body>
3
  • 1
    How do you get reference to your myDiv component? Do you use same ref for removing? Commented Dec 29, 2016 at 12:51
  • I have a global variable that contains it but I forgot to copy it Commented Dec 29, 2016 at 12:55
  • @VadimB Also with id='myDiv' corresponding HTMLElement gets exposed as global variable. Commented Dec 29, 2016 at 12:55

1 Answer 1

5

If ck is defined inside of Mouse it's not available in rel. Move it outside:

function cK() {
    alert('You\'ve clicked on myDiv!');
}
function Mouse() {
    myDiv.addEventListener('click', cK);
}
function rel() {
    myDiv.removeEventListener('click', cK);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Please also see VadimB's comment on question
Can the remove function, called before adding the event listener, cause issues?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.