skip to Main Content

I have an array that onclick randomly generates an image.
The thing is that i want to add some text to each image that also shows when onclick.

Im not sure how to add it to my existing array.

Here is how my code looks like.

This is the code that is used on my image that the user clicks on that generates a random image

<div class="fenetre">
  <a href="#" onClick="pickimg2(); return false;">
    <img src="image.png" name="randimg" border=0>
  </a>
</div>

Here is the array of images that randomly shows when i click the image above

<script>
var myImages1 = new Array();
myImages1.push("img1.png");
myImages1.push("img2.png");
myImages1.push("img3.png");
myImages1.push("img4.png");

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function pickimg2() {
  document.randimg.src = myImages1[getRandomInt(0, myImages1.length - 1)];
}
</script>

So how can i add text to my array with each image?

Thx!

2

Answers


  1. var myImages1 = new Array();
    myImages1.push({"image" :"img1.png","text": "your text here"});
    myImages1.push({"image" :"img2.png","text": "your text here"});
    myImages1.push({"image" :"img3.png","text": "your text here"});
    myImages1.push({"image" :"img4.png","text": "your text here"});
    
    
    function getValue() {
      myImages1.forEach(element => {
         element.text = "add sample text";
      }) 
      return myImages1
    }
    console.log(getValue())
    Login or Signup to reply.
  2. It is my solution:

    let myImages1 = new Array();
    myImages1.push({"image" :"img1.png","text": "text1"});
    myImages1.push({"image" :"img2.png","text": "text2"});
    myImages1.push({"image" :"img3.png","text": "text3"});
    myImages1.push({"image" :"img4.png","text": "text4"});
    
    
    function getRandomInt(min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    
    function pickimg2(e) {
      let item= myImages1[getRandomInt(0, myImages1.length - 1)];
      e.target.src=item.image;
      document.getElementById("text").textContent=item.text;
    }
    <div class="fenetre">
      <a href="#" onClick="pickimg2(event); return false;">
        <img src="image.png" name="randimg" border=0>    
      </a>
      <div id="text">
        
      </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search