skip to Main Content

In my sample code is not working perfectly can you please check and let me know where I’m wrong?

function clickButon (){
    var btn = document.getElementById('updateText');
     btn.addEventListener('click', function(){
        updateHTml();
        console.log('event click here ')
       // jsFileLoad();
     },true)
     
}    
function eventRemove(){
    var btn = document.getElementById('updateText');
    btn.removeEventListener('click', function(){
        console.log('event remove for btn')
    }, true)
}
window.onload = function(){
    clickButon();

    setTimeout(function(){
        eventRemove();
    }, 2000)
}

2

Answers


  1. To remove the event handler, you have to pass the same function that you passed when adding it.

    For example, here you would successfully remove the event handler

    function sameFunction() {
      console.log('test');
    }
    
    btn.addEventListener(sameFunction)
    btn.removeEventListener(sameFunction)
    

    Contraty to creating a new function when you’re removing the event listener:

    function sameFunction() {
      console.log('test');
    }
        
    btn.addEventListener(sameFunction)
    btn.removeEventListener(function() {
      console.log('test');
    });
    
    Login or Signup to reply.
  2. The function you are removing is not the same function you added. The only way to remove a listener is to give it the same function that is already added as a listener. For example:

    function updateTextClickListener(evt) {
      console.log('event click here')
    }
    
    function installUpdateTextClickListener() {
      var btn = document.getElementById('updateText');
      btn.addEventListener('click', updateTextClickListener, true)
    }    
    function uninstallUpdateTextClickListener() {
        var btn = document.getElementById('updateText');
        btn.removeEventListener('click', updateTextClickListener, true)
    }
    window.onload = function(){
      installUpdateTextClickListener();
    
      setTimeout(function(){
        uninstallUpdateTextClickListener();
      }, 2000)
    }
    <button id="updateText">Update Text</button>

    Note that if you create an identical function, it will still not work, because "identical" is not "same":

    const first  = function() { return 42; }
    const second = function() { return 42; }
    
    console.log(first === first)
    // true
    console.log(first === second)
    // false
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search