Home > OS >  JS - Can't give an element onclick twice
JS - Can't give an element onclick twice

Time:12-01

i am making a chess game i have a div as a block and in that div there is a button and a pawn-div, i have given each button an onclick to move my pawn, now to kill a pawn i want to give another onclick to the button but for some reason i can't do please help

my code

function hlblp(a) {
let pawn = document.getElementsByClassName("blp")[a]
let parent = Number.parseInt(pawn.parentElement.id)
hightlitght(parent)
for (let i=0; i<64; i  ) {
let block = document.getElementsByClassName("Btns")[i]
block.onclick = function() {movepawn(block, pawn)};
}}

function removepawn(b) {console.log(b[0])}

function hightlitght(a) {


if (var1==true) {
var1 = false

let var2 = a-10

var2 = var2 "b"


if (occupied[var2]==true) {
let b1 = a-20
b11 = "r" b1
let occ1 = b1 "b"
b11 = document.getElementsByClassName(b11)[0]
// this is where i want to give an second onclick
b11.onclick = function() {removepawn(b11)};

if ( occupied[occ1] == false ) {
if (
b1 < 89 && b1 > 80 ||
b1 < 79 && b1 > 70 ||
b1 < 69 && b1 > 60 ||
b1 < 59 && b1 > 50 ||
b1 < 49 && b1 > 40 ||
b1 < 39 && b1 > 30 ||
b1 < 29 && b1 > 20 ||
b1 < 19 && b1 > 10) {b11.style.display = "block";
}}
}}

CodePudding user response:

You shouldn't use:

block.onclick = function() { ... }

Because when second time you assing to onclick you are removing previous one.

You can create function which will combine both events but that is not elegant.

Or you can do it the right way with:

block.addEventListener('click', function() { ... });

CodePudding user response:

Please awlays use addEventListener instead of ELEMENT.onevent. If you need to remove the current onClick event and add a new one you can:

  • removeEventListener to remove the actual one. And then again addEventListener to reattach.
  • Or add an additional logic inside the already attached addEventListener callback to distinguish the purpose of different clicks.

LINKS:

addEventListener: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener removeEventListener: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener

  • Related