2

Been struggling for a while on this so I decided to craft up a jsfiddle to show an example:

gameworld  = document.getElementById('GameWorld');
character  = document.getElementById('c');

gameworld.addEventListener('click', function(e){
    console.log(e);
    character.style.left=''+e.offsetX+'px';
    character.style.top=''+e.offsetY+'px';
});

Fiddle here: http://jsfiddle.net/g43nxhcw/1/

If you click anywhere on the red container, you grab the offsetX, and offsetY. But, if you click on the tile, you grab its offset instead, which is causing the character to not move to that spot.

What I am trying to do is grab the GameWorld's offsetX and offsetY even if the tile is clicked upon, is that possible?

When looking at the console we can see that e.target shows which element the user has clicked on. This is about as close as I can get, because I need to find the offset's of the GameWorld's element when a parent child element of it, is clicked on.

I can get access to GameWorld's node when the img tile is clicked on, by accessing:

e.path[0], as pertinent here

Sadly, that is where I get stuck and not sure what to grab with the node tree.

Edit: I don't want to use pointer-events either because It seems like its a easy way out of the problem, and for collision detection later, it will become an issue.

Edit2: WARNING

I was using transform:translate(X,Y) on these VALUES and they DO NOT get passed to the DOM (for offsets) so if anyone gets stuck on this, remember to add top: and left: properties for the dom to catch the offsets & values.

NiCk Newman
  • 1,716
  • 7
  • 23
  • 48
  • 2
    On offsetX/offsetY in FF: http://stackoverflow.com/questions/11334452/event-offsetx-in-firefox – dekkard May 10 '15 at 19:47

2 Answers2

1

You can add the child’s offsetLeft and offsetTop properties. For arbitrary depths (it seemed cleaner):

var offsetX = e.offsetX;
var offsetY = e.offsetY;

var element = e.target;

while (element !== gameworld) {
    offsetX += element.offsetLeft;
    offsetY += element.offsetTop;
    element = element.parentNode;
}

character.style.left = offsetX + 'px';
character.style.top = offsetY + 'px';

Updated fiddle

Ry-
  • 218,210
  • 55
  • 464
  • 476
  • 1
    Ha, been struggling with this for months and you post a solution in minutes. My God. Will Mark in T-6min, thank you. – NiCk Newman May 10 '15 at 19:41
  • I just found out another problem.. I was using `transform: translate('+T[i].x+'px, '+T[i].y+'px);` to position the tiles and the `top`, and `left` properties weren't getting passed to the DOM....... Haha no freaking wonder why I was having so many issues. Learned my damn lesson though. – NiCk Newman May 10 '15 at 20:27
0

Note that if this is still buggy, you can substract target.offsetWidth/2 or target.offsetHeight/2 depending on the context. (because offsetLeft is calculated from the center of the current element.)

Ajeet Shah
  • 18,551
  • 8
  • 57
  • 87