nienn6 nienn6 - 5 months ago 10
Javascript Question

Random image click

So I got a site full of images and they are are all in random order, everytime you refresh the page. You have to search for a image which is always on a different place.

function randomWaldo() {
var randomNummer = Math.floor((Math.random() * 100) + 1);
document.getElementsByTagName('img')[randomNummer].src = "images/waldo.jpg";}


Now I want the first paragraph in my HTML to change when you click on that one image. How can I do this?

Answer

You can try to select the image who have the wanted source.

And add a class or id to your paragraph for readability.

document.querySelectorAll("img[src='images/waldo.jpg']")[0].onclick=function()
{
document.getElementById("paragraphid").innerHTML="You win";
};

Example

document.querySelectorAll("img[src='image/waldo.jpg']")[0].onclick=function()
{
  document.getElementById("rep").innerHTML="you win !";
}
img{
  height:100px;
  width:100px;
  }
<p id="rep"></p>
<img src="image/nok.jpg" alt="nok">
<img src="image/nok.jpg" alt="nok">
<img src="image/nok.jpg" alt="nok">
<img src="image/waldo.jpg" alt="waldo">
<img src="image/nok.jpg" alt="nok">

Comments