3

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
mjade
  • 539
  • 1
  • 4
  • 9
  • Search for “this keyword in JavaScript”. It has to do with how the function is invoked - “this” inside a function is normally the object used in the _expression_ to call the function (it can also be manually specified with call/apply). That said, it’s probably more clear at the end of the day to just to separate out the button handler and pass in the value itself in both cases. – user2864740 Jun 13 '20 at 18:21
  • All the information here: https://stackoverflow.com/q/3127429/2864740 – user2864740 Jun 13 '20 at 18:23

1 Answers1

2

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

 myFunction.call(btn);

this code basically invokes the function setting this to btn

6502
  • 112,025
  • 15
  • 165
  • 265