0

I am creating a div element and adding an onclick to drag the element around on the screen. The dragging itself is working as expected, but it doesn't work until I double click on the element. Any idea why I need to double click each element before I can drag them around the screen/What I can do to drag the element with a single click?

I didn't need to double click these elements until after I started building them dynamically from inside JS.

Here is the line adding the onclick:

node.onclick = function(){ 
   dragElement(document.getElementById(this.id)); 
}

Here is the entire function:

function buildCards(){
    for(let x=0;x<4;x++){
        for(let i=0;i<13;i++){

            var individualCard = new Object();
            individualCard.value = i;

            if(x == 0){
                individualCard.type = 'club';
                individualCard.color = 'black';
            }else if(x == 1){
                individualCard.type = 'spade';
                individualCard.color = 'black';
            }else if(x == 2){
                individualCard.type = 'heart';
                individualCard.color = 'red';
            }else{
                individualCard.type = 'diamond';
                individualCard.color = 'red';
            }

            individualCard.id = individualCard.color+'-'+individualCard.value+'-'+individualCard.type;

            deckOfCards.push(individualCard);

            let node = document.createElement('div');
            node.className = 'cards';
            node.setAttribute("id", individualCard.id);
            node.onclick = function(){ 
                dragElement(document.getElementById(this.id)); 
            }
            node.style.background = 'url("cards/cards.png") '+-(i*72)+'px '+-(x*96)+'px';
            document.getElementById('gameBoard').appendChild(node);
        }
    }
}

Per Goldie's comment I adjusted the onclick event to an event listener.

document.getElementById("gameBoard").addEventListener("click",function(e) { 
if (e.target && e.target.matches("div.cards")) { 
      console.log("Anchor element clicked! "+e.target.id);
} });```
MPStimpson
  • 336
  • 1
  • 3
  • 16
  • see answer here: https://stackoverflow.com/a/34896387/8156265 – full-stack Apr 22 '19 at 16:59
  • Hello, I adjusted it so it looks like: `document.getElementById("gameBoard").addEventListener("click",function(e) { if (e.target && e.target.matches("div.cards")) { console.log("Anchor element clicked! "+e.target.id); dragElement(e.target); } }); ` I now need to click an element once before I can move it, any other ideas? – MPStimpson Apr 22 '19 at 23:21

1 Answers1

0

I replaced the click listener with mousemove and it works just fine.

document.getElementById("gameBoard").addEventListener("mousemove",function(e) { 
    if (e.target && e.target.matches("div.cards")) { 
          console.log("Element id: "+e.target.id); 
    }});
MPStimpson
  • 336
  • 1
  • 3
  • 16