Skip to main content
sovie4711
Inspiring
January 23, 2018
Answered

event.target in JS/HTML5 Canvas [Event Bubbling]

  • January 23, 2018
  • 2 replies
  • 2302 views

Hello,

in AS3 i used to do this for event bubbling (using evt.target or evt.currentTarget).

mc1.addEventListener(MouseEvent.CLICK, myFunction);

function myFunction(evt:MouseEvent) {

evt.currentTarget.x=300;}

So i write the function only once and added the listener to multiple Targets(symbol instances).

mc2.addEventListener(MouseEvent.CLICK, myFunction);

mc3.addEventListener(MouseEvent.CLICK, myFunction);

How i have to re-write this in JS/HTML5 Canvas? I tried

this.mc1.addEventListener("click", myFunction.bind(this));

function myFunction(evt)

{this.evt.target.x=300;}

But it does not work.

    This topic has been closed for replies.
    Correct answer ClayUUID

    sovie4711  wrote

    How i have to re-write this in JS/HTML5 Canvas? I tried

    this.mc1.addEventListener("click", myFunction.bind(this));

    function myFunction(evt)

    {this.evt.target.x=300;}

    But it does not work.

    It's not working because evt is not a property of this, it's an argument being passed into the event handler function. Get rid of the this. in front of it.

    2 replies

    ClayUUIDCorrect answer
    Brainiac
    January 23, 2018

    sovie4711  wrote

    How i have to re-write this in JS/HTML5 Canvas? I tried

    this.mc1.addEventListener("click", myFunction.bind(this));

    function myFunction(evt)

    {this.evt.target.x=300;}

    But it does not work.

    It's not working because evt is not a property of this, it's an argument being passed into the event handler function. Get rid of the this. in front of it.

    Joseph Labrecque
    Community Expert
    January 23, 2018

    Write a command to express "evt" or even "this" in the browser console via something like console.log(evt);

    What does it spit out?

    sovie4711
    sovie4711Author
    Inspiring
    January 23, 2018

    alert(event.target);//[object HTMLCanvasElement]

    alert(evt.target) //[Shape (name=null)]

    console.log(evt.target); //a {_listeners: null, _captureListeners: null, alpha: 1, cacheCanvas: null, cacheID: 0, …}

    console.log(event.target); //<canvas id="canvas" .....">

    So i can not grab the "object" in Canvas that is actually clicked?
    I ask because i don't like to write the function for every single Symbol (which should do the same thing on Click Event).

    Joseph Labrecque
    Community Expert
    January 23, 2018

    You can do this. For instance, I have the following code and 2 MCs on the stage:

    this.b1.name = "button_one";

    this.b1.addEventListener("click", myFunction.bind(this));

    this.b2.name = "button_two";

    this.b2.addEventListener("click", myFunction.bind(this));

    function myFunction(e) {

    console.dir(e);

    }

    Here is what is output:

    So I'd go with e.currentTarget.x instead.