0

I an attaching event listeners in input box by using ID. so its working fine but I want to remove event listeners its will not work for me.

document.getElementById("myInput").addEventListener("keyup", function({
    console.log(document.getElementById("myInput").value);
});


  document.getElementById("myInput").removeEventListener("keyup",function() {

});
Anupam
  • 201
  • 2
  • 4
  • 11

3 Answers3

5

The second argument needs to be the event listener you want to remove (so you need to keep a reference to that function around instead of putting a function expression directly as the argument to addEventListener).

You're passing it a brand new function. It doesn't get removed, because that function wasn't listening in the first place.

var in = document.getElementById("myInput");

function myListener (event) {
    console.log(in.value);
}

in.addEventListener("keyup", myListener);
in.removeEventListener("keyup", myListener);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2

Try that

var fn = function({
    console.log(document.getElementById("myInput").value);
}

document.getElementById("myInput").addEventListener("keyup", fn);
document.getElementById("myInput").removeEventListener("keyup", fn);
Arthur
  • 4,870
  • 3
  • 32
  • 57
1
var body =
        document.querySelector('body'),
    clickTarget =
        document.getElementById('click-target'),
    mouseOverTarget =
        document.getElementById('mouse-over-target'),
    toggle = false;

function makeBackgroundYellow() {
    'use strict';

    if (toggle) {
        body.style.backgroundColor = 'white';
    } else {
        body.style.backgroundColor = 'yellow';
    }

    toggle = !toggle;
}

clickTarget.addEventListener('click',
    makeBackgroundYellow,
    false
);

mouseOverTarget.addEventListener('mouseover', function () {
    'use strict';

    clickTarget.removeEventListener('click',
        makeBackgroundYellow,
        false
    );
});


target.removeEventListener(type, listener[, options]);
target.removeEventListener(type, listener[, useCapture]);

the second argument is the eventlistener you want to remove, see this

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Francesco Taioli
  • 2,687
  • 1
  • 19
  • 34