How to disable clicking on an image?

Viewed 316

I am trying to make a memory game using JavaScript and jQuery and now I want to disable clicking the image (card) that is opened on click. I have tried img.onclick=false, img.onclick=null, but it does not work. Below is a part of my code.

$(document).ready(function() {
  $("img").click(function() {
    checkIfMatch(this);
  });
});

function checkIfMatch(img) {
  arrayIMG.push(img);
  img.onclick = false; //here I want to disable the clicking
}
2 Answers

The easiest tweak would be to only push the image to the array if it's not already in it:

function checkIfMatch(img) {
  if (!arrayIMG.includes(img)) {
    arrayIMG.push(img);
    // do other stuff when an image is clicked, if any
  }
}

If you don't need to do other stuff when a new image is clicked, you could make things even easier by using a Set instead (which will automatically condense duplicates):

const arrayIMG = new Set();
function checkIfMatch(img) {
  arrayIMG.add(img);
}

To turn off a jquery click handler, you use:

$(..).off("click");

this is the opposite of $("..").on("click", function... which is can be written short-hand as $(..).click(function...

$(document).ready(function() {
  $("img").click(function() {
    checkIfMatch(this);
  });
});

var arrayIMG = [];
function checkIfMatch(img) {
  arrayIMG.push(img);
  //img.onclick = false; //here I want to disable the clicking
  $(img).off("click");
  
  // toggle to show that it only gets called once
  $(img).toggleClass("active");
  console.log("click")
}
.active { border: 5px solid red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://i.stack.imgur.com/XZ4V5.jpg" width=320/>
<img src="https://i.stack.imgur.com/7bI1Y.jpg" width=320/>


Alternatively, you can use a singe-click mechanism:

$(..).one("click", function 

which will automatically turn off the click event once clicked

$(document).ready(function() {
  $("img").one("click", function() {
    checkIfMatch(this);
  });
});

var arrayIMG = [];
function checkIfMatch(img) {
  arrayIMG.push(img);

  // no need to "turn off" click as only run once
  
  // toggle to show that it only gets called once
  $(img).toggleClass("active");
  console.log("click")
}
.active { border: 5px solid red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://i.stack.imgur.com/XZ4V5.jpg" width=320/>
<img src="https://i.stack.imgur.com/7bI1Y.jpg" width=320/>

Related