Xephoriath
Xephoriath

Reputation: 171

How do I reference and manipulate a targeted object from a called function outside the function's scope?

I am trying to create a program (chess) such that div elements created via JS dom can be dragged with your cursor. However I have it setup so I add an event listener to each piece created which calls a function adding an event listener to the window which then calls the function to move each piece. I can't reference "this" since the target of the movement function is the window and not the piece with the "mousedown" event. Can I reference the intended target from a completely different function?

I'd tried to do var targetedPiece=this.targetedPiece in the "mouseDown" function Followed by targetedPiece.style.left=cursor.x+'px' in the "movePiece" function but to no avail.

//Basic chess board creation, creating elements with DOM
var board = document.getElementById('gameBoard');
var newSquare = document.createElement('div');
var newPiece = document.createElement('div');
newPiece.addEventListener('mousedown', mouseDown, false);
newSquare.appendChild(newPiece);
board.appendChild(newSquare);

//Assigns cursor position to cursor.x & cursor.y respectively
function getCursorPos(e) {
  let cursor = {
    x: e.pageX - board.offsetLeft,
    y: e.pageY - board.offsetTop
  };
}

//Registers last mouseup/mousedown actions
function mouseDown(targetedPiece) {
  window.addEventListener('mousemove', movePiece, true);
  //This is the function I'm calling with the piece
}

function mouseUp() {
  window.removeEventListener('mousemove', movePiece, true);
}

//Function for actually moving pieces with cursor
function movePiece() {
  //What do I put here? The targeted piece calls mouseDown, can I reference it in this function?
  //The idea is targetedPiece.style.left=cursor.x & targetedPiece.style.top=cursor.y
}

board.addEventListener('mousemove', getCursorPos, true);
window.addEventListener('mouseup', mouseUp, false);
<div id='gameBoard'></div>

Upvotes: 1

Views: 38

Answers (0)

Related Questions