TheOne
TheOne

Reputation: 15

Can i use removeEventListener in this way?

I am trying to toggle event listener on child elements, can I use removeEventListener like in this code:

    function changeColor(){
        container.addEventListener('click',function color(){
            if(activatePen==true){
                let slab=document.querySelectorAll('div .item');
                slab.forEach((slabs)=>{
                    slabs.addEventListener('mouseover', function changeGridColor(){
                        slabs.setAttribute('style','background: blue; font-size:30px; text-align: center; border:0px solid white');
                    });
                });
            }
            else{
                let slab=document.querySelectorAll('div .item');
                slab.forEach((slabs)=>{
                    slabs.removeEventListener('mouseover', function changeGridColor(){
                        slabs.setAttribute('style','background: white; font-size:30px; text-align: center; border:0px solid white');
                    });
                });
            }
        });
    }

Upvotes: 1

Views: 108

Answers (2)

Barmar
Barmar

Reputation: 781210

You need to use a named function in order to remove it. Event listener functions receive an Event object as the parameter, you can get the target element from that.

function changeGridColor(e) {
  e.currentTarget.setAttribute('style', 'background: blue; font-size:30px; text-align: center; border:0px solid white');
}

var activatePen = false;

document.querySelector("#activate").addEventListener("click", function() {
  activatePen = !activatePen;
  changeColor();
});

function changeColor() {
  let slab = document.querySelectorAll('div .item');
  if (activatePen) {
    slab.forEach((slabs) =>
      slabs.addEventListener('mouseover', changeGridColor));
  } else {
    slab.forEach((slabs) =>
      slabs.removeEventListener('mouseover', changeGridColor));
  }
}

changeColor();
<div id="container" <div id>
  <div class="item">Item 1</div>
  <div class="item">Item 2</div>
  <div class="item">Item 3</div>
</div>

<button id="activate">Toggle hover</button>

Upvotes: 2

Jax-p
Jax-p

Reputation: 8531

No. You have 2 declaration of some function - it allocates 2 different references. You can:

Create function once and call it by a name

const changeGridColor=(e)=>{
  // e.currentTarget.setAttribute()
}
slabs.addEventListener('mouseover',changeGridColor);
slabs.removeEventListener('mouseover',changeGridColor);

Upvotes: 1

Related Questions