Los resultados de tu búsqueda

    element.addEventListener

    Resumen

    addEventListener() Registra un evento a un objetivo en especifico. El ObJeto especifico Puede ser un simple elemento en un archivo, el mismo  documento , una ventana, o un  XMLHttpRequest.

    Para registrar más de un eventListener, llama addEventListener() para el mismo elemento pero para diferentes tipos de eventos o paramentros de caputra.

    Sintaxis

    target.addEventListener(tipo, listener[, useCapture]);
    target.addEventListener(tipo, listener[, useCapture, aWantsUntrusted  ]); // Gecko/Mozilla only
    tipo
    Una cadena representando el  tipo de evento a escuchar.
    listener
    El objeto que recibe una notificación cuando un evento de el tipo especificado ocurre. Debe ser un objeto implementando la interfaz EventListener o solo una function en JavaScript.
    useCapture Optional
    Si es true, useCapture indica que el usuario desea iniciar la captura.   Después de iniciar la captura, todos los eventos del tipo especificado serán lanzados al listener registrado antes de comenzar  a ser controlados por algún EventTarget que esté por debajo en el arbol DOM del documento. Events which are bubbling upward through the tree will not trigger a listener designated to use capture. See DOM Level 3 Events for a detailed explanation. Note that this parameter is not optional in all browser versions. If not specified, useCapture is false.
    aWantsUntrusted
    If true, the event can be triggered by untrusted content. See Interaction between privileged and non-privileged pages.
    Note: useCapture became optional only in more recent versions of the major browsers; for example, it was not optional prior to Firefox 6. You should provide that parameter for broadest compatibility.

    Ejemplo

    <!DOCTYPE html>
    <html>
    <head>
    <title>DOM Event Example</title>
    
    <style>
    #t { border: 1px solid red }
    #t1 { background-color: pink; }
    </style>
    
    <script>
    // Function to change the content of t2
    function modifyText() {
      var t2 = document.getElementById("t2");
      t2.firstChild.nodeValue = "three";    
    }
     
    // Function to add event listener to t
    function load() { 
      var el = document.getElementById("t"); 
      el.addEventListener("click", modifyText, false); 
    } 
    
    document.addEventListener("DOMContentLoaded", load, false);
    </script>
    
    </head>
    <body>
    
    <table id="t"> 
       <tr><td id="t1">one</td></tr>
       <tr><td id="t2">two</td></tr>
    </table>
    
    </body> 
    </html> 
    

    Ver en el jsFiddle

    In the above example, modifyText() is a listener for click events registered using addEventListener(). A click anywhere on the table will bubble up to the handler and run modifyText().

    If you want to pass parameters to the listener function, you have to use an anonymous function.

    <!DOCTYPE html>
    <html>
    <head>
    <title>DOM Event Example</title>
    
    <style>
    #t { border: 1px solid red }
    #t1 { background-color: pink; }
    </style>
    
    <script>
    
    // Function to change the content of t2
    function modifyText(new_text) {
      var t2 = document.getElementById("t2");
      t2.firstChild.nodeValue = new_text;    
    }
     
    // Function to add event listener to t
    function load() { 
      var el = document.getElementById("t"); 
      el.addEventListener("click", function(){modifyText("four")}, false); 
    } 
    </script>
    
    </head>
    <body onload="load();">
    
    <table id="t">
      <tr><td id="t1">one</td></tr>
      <tr><td id="t2">two</td></tr>
    </table>
    
    </body>
    </html>
    

    Notas

    ¿Porqué utilizar addEventListener?

    addEventListener is the way to register an event listener as specified in W3C DOM. Its benefits are as follows:

    • It allows adding more than a single handler for an event. This is particularly useful for DHTML libraries or Mozilla extensions that need to work well even if other libraries/extensions are used.
    • It gives you finer-grained control of the phase when the listener gets activated (capturing vs. bubbling)
    • It works on any DOM element, not just HTML elements.

    The alternative, older way to register event listeners is described below.

    Adding a listener during event dispatch

    If an EventListener is added to an EventTarget while it is processing an event, it will not be triggered by the current actions but may be triggered during a later stage of event flow, such as the bubbling phase.

    Multiple identical event listeners

    If multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded. They do not cause the EventListener to be called twice, and since the duplicates are discarded, they do not need to be removed manually with the removeEventListener method.

    The value of this within the handler

    It is often desirable to reference the element from which the event handler was fired, such as when using a generic handler for a series of similar elements. When attaching a function using addEventListener() the value of this is changed—note that the value of this is passed to a function from the caller.

    In the example above, the value of this within modifyText() when called from the click event is a reference to the table 't'. This is in contrast to the behavior that occurs if the handler is added in the HTML source:

    <table id="t" onclick="modifyText();">
      . . .
    

    The value of this within modifyText() when called from the onclick event will be a reference to the global (window) object.

    Note: JavaScript 1.8.5 introduces the Function.prototype.bind() method, which lets you specify the value that should be used as this for all calls to a given function. This lets you easily bypass problems where it's unclear what this will be, depending on the context from which your function was called. Note, however, that you'll need to keep a reference to the listener around so you can later remove it.

    This is an example with and without bind:

    var Something = function(element)
    {
      this.name = 'Something Good';
      this.onclick1 = function(event) {
        console.log(this.name); // undefined, as this is the element
      };
      this.onclick2 = function(event) {
        console.log(this.name); // 'Something Good', as this is the binded Something object
      };
      element.addEventListener('click', this.onclick1, false);
      element.addEventListener('click', this.onclick2.bind(this), false); // Trick
    }
    

    A problem in the example above is that you cannot remove the listener with bind. Another solution is using a special function called handleEvent to catch any events:

    var Something = function(element)
    {
      this.name = 'Something Good';
      this.handleEvent = function(event) {
        console.log(this.name); // 'Something Good', as this is the Something object
        switch(event.type) {
          case 'click':
            // some code here...
            break;
          case 'dblclick':
            // some code here...
            break;
        }
      };
    
      // Note that the listeners in this case are this, not this.handleEvent
      element.addEventListener('click', this, false);
      element.addEventListener('dblclick', this, false);
    
      // You can properly remove the listners
      element.removeEventListener('click', this, false);
      element.removeEventListener('dblclick', this, false);
    }
    

    Legacy Internet Explorer and attachEvent

    In Internet Explorer versions prior to IE 9, you have to use attachEvent rather than the standard addEventListener. To support IE, the example above can be modified to:

    if (el.addEventListener) {
      el.addEventListener('click', modifyText, false); 
    } else if (el.attachEvent)  {
      el.attachEvent('onclick', modifyText);
    }
    

    There is a drawback to attachEvent, the value of this will be a reference to the window object instead of the element on which it was fired.

    Older way to register event listeners

    addEventListener() was introduced with the DOM 2 Events specification. Before then, event listeners were registered as follows:

    // Pass a function reference — do not add '()' after it, which would call the function!
    el.onclick = modifyText;
    
    // Using a function expression
    element.onclick = function() {
        // ... function logic ...
    };
    

    This method replaces the existing click event listener(s) on the element if there are any. Similarly for other events and associated event handlers such as blur (onblur), keypress (onkeypress), and so on.

    Because it was essentially part of DOM 0, this method is very widely supported and requires no special cross–browser code; hence it is normally used to register event listeners dynamically unless the extra features of addEventListener() are needed.

    Memory issues

    var i;
    var els = document.getElementsByTagName('*');
    
    // Case 1
    for(i=0 ; i<els.length ; i++){
      els[i].addEventListener("click", function(e){/*do something*/}, false});
    }
    
    // Case 2
    function processEvent(e){
      /*do something*/
    }
    
    for(i=0 ; i<els.length ; i++){
      els[i].addEventListener("click", processEvent, false});
    }
    
    

    In the first case, a new (anonymous) function is created at each loop turn. In the second case, the same previously declared function is used as an event handler. This results in smaller memory consumption. Moreover, in the first case, since no reference to the anonymous functions is kept, it is not possible to call element.removeEventListener because we do not have a reference to the handler, while in the second case, it's possible to do myElement.removeEventListener("click", processEvent, false).

    Browser compatibility

    Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
    Basic support 1.0 1.0 (1.7 or earlier) 9.0 7 1.0
    useCapture made optional 1.0 6.0 9.0 11.60 (Yes)
    Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
    Basic support 1.0 1.0 (1.0) 9.0 6.0 1.0

    Gecko notes

    • Prior to Firefox 6, the browser would throw if the useCapture parameter was not explicitly false. Prior to Gecko 9.0 (Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6), addEventListener() would throw an exception if the listener parameter was null; now the method returns without error, but without doing anything.

    WebKit notes

    • Although WebKit has explicitly added [optional] to the useCapture parameter as recently as June 2011, it had been working before the change. The new change landed in Safari 5.1 and Chrome 13.

    See Also

    Specification

    Etiquetas y colaboradores del documento

    Colaboradores de esta página: edulon, Chacho
    Última actualización por: edulon,