Search code examples
javascriptcallbackaddeventlistenerevent-listener

Pass Element to Event Listener Callback Function


In the following code:

document.getElementById( 'elem' ).addEventListener( 'blur', function() {
    myScript();
});

How can I pass the document.getElementById( 'elem' ) object to myScript()? I was thinking of something like the keyword "this," so I can then act on the element in the callback function.


Solution

  • You have four ways to pass the object this

    Bind the this object and call the function:

    This approach should be used if you need to execute some logic before myScript() execution

    function myScript() {
      console.log(this.id);
    }
    
    document.getElementById('elem').addEventListener('click', function() {
      myScript.bind(this)();
    });
    <button id="elem">Click me!</button>

    Call the function myScript using function call:

    This approach should be used if you need to execute some logic before myScript() execution

    Also read about function Function.prototype.apply().

    function myScript() {
      console.log(this.id);
    }
    
    document.getElementById('elem').addEventListener('click', function() {
      myScript.call(this);
    });
    <button id="elem">Click me!</button>

    Pass the function directly:

    function myScript() {
      console.log(this.id);
    }
    
    document.getElementById('elem').addEventListener('click', myScript);
    <button id="elem">Click me!</button>

    Or pass the object this:

    function myScript(element) {
      console.log(element.id);
    }
    
    document.getElementById('elem').addEventListener('click', function() {
      myScript(this); //Here you will need to use the param.
    });
    <button id="elem">Click me!</button>

    Resource