How to pass this element to another function from inside function of event listener?

Viewed 177

I have an event listener of a parent div and a button using the same function. while the one with the parent div I only want the it to go to my function if parent area is click and not its children. This is what I have so far:

btn.addEventLister("click", myFunction);

div.addEventListener("click", function (e) {
      if(e.currentTarget === e.target){
         myFunction();
      }
   }); 

function myFunction() {
  var type = this.getAttribute('data-type');
  // do something here
}

The btn listener works, but somehow the div listener doesn't work. Somehow its seems like it doesn't recognize the "this". Any idea how to solve this?

1 Answers

You need to pass the button explicitly... for example with

 myFunction.call(btn);

this code basically invokes the function setting this to btn

Related