How to return value from addEventListener

jdleung picture jdleung · Nov 3, 2015 · Viewed 20.4k times · Source

I use a javascript to catch the x and y position when user click a link, by now, I can make it works, but I want it to return the two values to function init() when it is called. How can I do it?

<script type="text/javascript">

  document.addEventListener("DOMContentLoaded", init, false);

  function init()
  {
    var canvas = document.getElementById("canvas");
    canvas.addEventListener("mousedown", getPosition, false);

    // how can I get the return values here?

  }

  function getPosition(event)
  {
    var x = new Number();
    var y = new Number();
    var canvas = document.getElementById("canvas");

    if (event.x != undefined && event.y != undefined)
    {
      x = event.x;
      y = event.y;
    }
    else
    {
      x = event.clientX + document.body.scrollLeft +
          document.documentElement.scrollLeft;
      y = event.clientY + document.body.scrollTop +
          document.documentElement.scrollTop;
    }

    x -= canvas.offsetLeft;
    y -= canvas.offsetTop;

    alert("x: " + x + "  y: " + y); // here can print the correct position

    // if I add the two values here, and return them. How can I receive the values in funciton init()
    // var clickPosition={"x":x, "y":y};
    // return clickPosition;
  }

</script>

Answer

Jamiec picture Jamiec · Nov 3, 2015

Where you have the comment, you will never be able to access the variables, the event has not occurred yet.

Instead, what you can do is pass an anonymous function to the event handler, call your method which returns a value and use it as appropriate

function init()
{
    var canvas = document.getElementById("canvas");
    canvas.addEventListener("mousedown", function(event){
        var result = getPosition(event);

        // result is your return value
    }, false);

}