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);
} });```