이 번역은 완료되지 않았습니다. 이 문서를 번역해 주세요.

EventTarget.removeEventListener() 메서드는 이전에EventTarget.addEventListener()로 EventTarget 에 등록했던 이벤트 리스너를 제거합니다. 이 이벤트 리스너는 이벤트 종류와 이벤트 리스너 함수 자체의 조합으로 식별되어 제거되며, 등록시 제공했던 다양한 옵션과 일치하는 이벤트 리스너만 제거할 수 있습니다.  Matching event listeners for removal를 참고하세요.

Syntax

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

Parameters

type
제거할 이벤트 리스너의 이벤트 타입을 지정합니다.
listener
이벤트 타깃에서 제거할 이벤트 핸들러 함수, EventListener를 지정합니다.
options Optional
이벤트 리스너에 대한 특징, 즉 제거할 이벤트 리스너의 옵션들을 지정합니다. 지정할 수 있는 옵션들은 아래와 같습니다.
  • capture: 이 이벤트 타입의 이벤트들이 DOM 트리 내 모든 어떤 EventTarget 에 디스패치되기 전에  등록된 listener 들을 먼저 처리하도록 만들지 말지를 결정하는 Boolean 값.
  • mozSystemGroup: Available only in code running in XBL or in Firefox' chrome, it is a Boolean defining if the listener is added to the system group. (비표준)
useCapture Optional
Specifies whether the EventListener to be removed is registered as a capturing listener or not. If this parameter is absent, a default value of false is assumed.
If a listener is registered twice, one with capture and one without, remove each one separately. Removal of a capturing listener does not affect a non-capturing version of the same listener, and vice versa.

Return value

undefined.

Matching event listeners for removal

Given an event listener previously added by calling addEventListener(), you may eventually come to a point at which you need to remove it. Obviously, you need to specify the same type and listener parameters to removeEventListener(), but what about the options or useCapture parameters?

While addEventListener() will let you add the same listener more than once for the same type if the options are different, the only option removeEventListener() checks is the capture/useCapture flag. Its value must match for removeEventListener() to match, but the other values don't.

For example, consider this call to addEventListener():

element.addEventListener("mousedown", handleMouseDown, true);

Now consider each of these two calls to removeEventListener():

element.removeEventListener("mousedown", handleMouseDown, false);     // Fails
element.removeEventListener("mousedown", handleMouseDown, true);      // Succeeds

The first call fails because the value of useCapture doesn't match. The second succeeds, since useCapture matches up.

Now consider this:

element.addEventListener("mousedown", handleMouseDown, { passive: true });

Here, we specify an options object in which passive is set to true, while the other options are left to the default value of false.

Now look at each of these calls to removeEventListener() in turn. Any of them in which capture or useCapture is true fail; all others succeed. Only the capture setting matters to removeEventListener().

element.removeEventListener("mousedown", handleMouseDown, { passive: true });     // Succeeds
element.removeEventListener("mousedown", handleMouseDown, { capture: false });    // Succeeds
element.removeEventListener("mousedown", handleMouseDown, { capture: true });     // Fails
element.removeEventListener("mousedown", handleMouseDown, { passive: false });    // Succeeds
element.removeEventListener("mousedown", handleMouseDown, false);                 // Succeeds
element.removeEventListener("mousedown", handleMouseDown, true);                  // Fails

It's worth noting that some browser releases have been inconsistent on this, and unless you have specific reasons otherwise, it's probably wise to use the same values used for the call to addEventListener() when calling removeEventListener().

Notes

If an EventListener is removed from an EventTarget while it is processing an event, it will not be triggered by the current actions. An EventListener will not be invoked for the event it was registered for after being removed. However, it can be reattached.

Calling removeEventListener() with arguments that do not identify any currently registered EventListener on the EventTarget has no effect.

Example

This example shows how to add a click-based event listener and remove a mouseover-based event listener.

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
    );
});

Specifications

Specification Status Comment
DOM
The definition of 'EventTarget.removeEventListener()' in that specification.
Living Standard  
DOM4
The definition of 'EventTarget.removeEventListener()' in that specification.
Obsolete  
Document Object Model (DOM) Level 2 Events Specification
The definition of 'EventTarget.removeEventListener()' in that specification.
Obsolete Initial definition

Browser compatibility

 

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
removeEventListenerChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 9
Full support 9
No support 6 — 11
Notes Alternate Name
Notes Older versions of IE supported an equivalent, proprietary EventTarget.detachEvent() method.
Alternate Name Uses the non-standard name: detachEvent
Opera Full support 7Safari Full support 1WebView Android Full support 1Chrome Android Full support 18Edge Mobile Full support YesFirefox Android Full support 4Opera Android Full support 10.1Safari iOS Full support 1Samsung Internet Android Full support Yes
useCapture parameter optionalChrome Full support 1Edge Full support YesFirefox Full support 6IE Full support 9Opera Full support 11.6Safari Full support YesWebView Android Full support 1Chrome Android Full support 18Edge Mobile Full support YesFirefox Android Full support 6Opera Android Full support 12Safari iOS Full support YesSamsung Internet Android Full support Yes
type and listener parameters optional.Chrome No support 1 — 49Edge Full support YesFirefox Full support YesIE Full support YesOpera Full support YesSafari Full support YesWebView Android No support 1 — 49Chrome Android No support 18 — 49Edge Mobile Full support YesFirefox Android Full support YesOpera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes
Form with options object supported (third parameter can be either options or a Boolean, for backwards compatibility)Chrome Full support 49Edge Full support YesFirefox Full support 49IE No support NoOpera Full support YesSafari Full support 10WebView Android Full support 49Chrome Android Full support 49Edge Mobile Full support YesFirefox Android Full support 49Opera Android Full support YesSafari iOS Full support 10Samsung Internet Android Full support 5.0

Legend

Full support  
Full support
No support  
No support
See implementation notes.
See implementation notes.
Uses a non-standard name.
Uses a non-standard name.

Polyfill to support older browsers

addEventListener() and removeEventListener() are not present in older browsers. You can work around this by inserting the following code at the beginning of your scripts, allowing the use of addEventListener() and removeEventListener() in implementations that do not natively support it. However, this method will not work on Internet Explorer 7 or earlier, since extending the Element.prototype was not supported until Internet Explorer 8.

if (!Element.prototype.addEventListener) {
  var oListeners = {};
  function runListeners(oEvent) {
    if (!oEvent) { oEvent = window.event; }
    for (var iLstId = 0, iElId = 0, oEvtListeners = oListeners[oEvent.type]; iElId < oEvtListeners.aEls.length; iElId++) {
      if (oEvtListeners.aEls[iElId] === this) {
        for (iLstId; iLstId < oEvtListeners.aEvts[iElId].length; iLstId++) { oEvtListeners.aEvts[iElId][iLstId].call(this, oEvent); }
        break;
      }
    }
  }
  Element.prototype.addEventListener = function (sEventType, fListener /*, useCapture (will be ignored!) */) {
    if (oListeners.hasOwnProperty(sEventType)) {
      var oEvtListeners = oListeners[sEventType];
      for (var nElIdx = -1, iElId = 0; iElId < oEvtListeners.aEls.length; iElId++) {
        if (oEvtListeners.aEls[iElId] === this) { nElIdx = iElId; break; }
      }
      if (nElIdx === -1) {
        oEvtListeners.aEls.push(this);
        oEvtListeners.aEvts.push([fListener]);
        this["on" + sEventType] = runListeners;
      } else {
        var aElListeners = oEvtListeners.aEvts[nElIdx];
        if (this["on" + sEventType] !== runListeners) {
          aElListeners.splice(0);
          this["on" + sEventType] = runListeners;
        }
        for (var iLstId = 0; iLstId < aElListeners.length; iLstId++) {
          if (aElListeners[iLstId] === fListener) { return; }
        }     
        aElListeners.push(fListener);
      }
    } else {
      oListeners[sEventType] = { aEls: [this], aEvts: [ [fListener] ] };
      this["on" + sEventType] = runListeners;
    }
  };
  Element.prototype.removeEventListener = function (sEventType, fListener /*, useCapture (will be ignored!) */) {
    if (!oListeners.hasOwnProperty(sEventType)) { return; }
    var oEvtListeners = oListeners[sEventType];
    for (var nElIdx = -1, iElId = 0; iElId < oEvtListeners.aEls.length; iElId++) {
      if (oEvtListeners.aEls[iElId] === this) { nElIdx = iElId; break; }
    }
    if (nElIdx === -1) { return; }
    for (var iLstId = 0, aElListeners = oEvtListeners.aEvts[nElIdx]; iLstId < aElListeners.length; iLstId++) {
      if (aElListeners[iLstId] === fListener) { aElListeners.splice(iLstId, 1); }
    }
  };
}

See also

문서 태그 및 공헌자

이 페이지의 공헌자: mdnwebdocs-bot, jay94ks
최종 변경자: mdnwebdocs-bot,