Home > Enterprise >  How to check if an image is clicked in a function with JavaScript?
How to check if an image is clicked in a function with JavaScript?

Time:11-20

I hope this is the right place to ask, I am new to html and javascript. I want to make a simple "game". The part where I got stuck is that everytime you click on any image in the different html screens the function set to that image will be executed. It has no order to it. For example you can press an image that is supposed to be at the end of the game even if you just started it. I think I know where the problem is but not sure how to fix it.

I believe it has something to do with this part of my html code: `

<img id="img1" src="map.jpeg" onclick="myFunction()"/>

Which means that everytime you click the image the function "myFunction()" will be executed.

This is the myFunction code, that shows a "you have found the map" box and then shows an image that has display:"none" in a html file :

  var r = confirm("You have found the map!");
  if (r == true) {
    document.getElementById("img2").style.display = "inline";
  } else {
  }
}

I think the solution to my problem would maybe be to have the onclick="myFunction()" part in the javascript function somehow, that first checks if the image has been clicked (once) and then continuing with the condition I set. Is there any way to do that? Thankful for any help!

CodePudding user response:

What is this "confirm" function? Also, document.getElementById("img2").style.display = "inline"; won't display a new image

CodePudding user response:

You can count the number of clicks in your function and base your logic on the number of clicks.

I've attempted to use some of the code you provided in my answer below. Please run the snippet and look at the notes in the javascript to understand what's happening.

// set clicks variable to 0, we will use this var to count the number of clicks on the image
var clicks = 0;

// declare function to handle clicks
function handleClicks() {
  //whenever this function runs, it will increase the clicks count by 1
  clicks  = 1;
  document.getElementById("clicks").innerHTML = clicks;
  // if number of clicks is greater than one then show image 2
  if (clicks > 1) {
    console.log('this image has already been clicked '   clicks   ' times.')
    document.getElementById("img2").style.display = "inline";
  } else {
    // if clicks aren't greater than 1 do something else
    console.log('this is the first time you clicked this image.')
  }
}
<div>
  <img id="img1" style="width: 25%;" src="https://cdn.pixabay.com/photo/2022/10/03/23/41/house-7497001_960_720.png" onclick="handleClicks()" />

  <img id="img2" style="display:none; width: 25%" src="https://cdn.pixabay.com/photo/2022/09/25/23/28/android-7479380_960_720.png" onclick="onClick()" />
  <br/>
  <p id="clicks"></p>
</div>

  • Related