3

Is it possible to set event.target manually at the time of adding event handler so that offsetX and offsetY are always relative to that target.

<div id="outer">
  <div class="inner"/>
  <div class="inner"/>
</div>

<script>
  document.getElementById("outer").addEventListener("click", function(){
    console.log(offsetX); // this will give offsetX relative to div.inner
                          // but i want offsetX relative to div#outer
  });
</script>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user2576951
  • 198
  • 1
  • 9
  • Because the event is on th outer div. Try with jQuery and 'next()' or 'children()' see here http://stackoverflow.com/questions/10567709/javascript-get-child-element – toesslab Jan 27 '14 at 14:38

1 Answers1

0

You should add a parameter to your addEventListener. It will end up looking like this:

document.getElementById("outer").addEventListener("click", function(ev) {
    console.log(ev.offsetX); }

ev now captures the event, and contains certain properties that you use use. offsetY will also be available. If that doesn't work, you should look at this SO post on mouse positions. You might be able to use pageX and pageY, or other properties that ev has.

Matt
  • 437
  • 3
  • 10