irfan spi irfan spi - 3 months ago 14
CSS Question

changing image src from array using jquery

I want to change the src of a few images. The urls are stored in a array randomly but the pictures are not showing. The images are stored in an

/img
folder.

var images=["img/Square.png","img/Star.png","img/Circle.png","img/Triangle.png","img/Ellipse.png","img/Rectangle.png"];

var image1 = Math.floor((Math.random() * 6) + 1);
var image2 = Math.floor((Math.random() * 6) + 1);
var image3 = Math.floor((Math.random() * 6) + 1);

$("#img1").attr("src",images[image1]);
$("#img2").attr("src",images[image2]);
$("#img3").attr("src",images[image3]);


My html Code is :

<div class="tag1" >
<img id="img1" class="img-responsive" src="" alt="" width="25%" />
<img id="img2" class="img-responsive" src="" alt="" width="25%" style="margin-left:10%;" >
<img id="img3" class="img-responsive" src="" alt="" width="25%" style="margin-left:10%;" >

Answer

"images" is not a string its a variable(array).

Try this,

 $("#img1").attr("src", images[image1]);

updated (after comment):

your random value sometimes gets 6 which is not present in the array change it to 5

  var image1 = Math.floor((Math.random() * 5) + 1);

and add all of your code inside ready function.

$(function(){
      var images=["img/Square.png","img/Star.png","img/Circle.png","img/Triangle.png","img/Ellipse.png","img/Rectangle.png"];

     var image1 = Math.floor((Math.random() * 5) + 1);
     var image2 = Math.floor((Math.random() * 5) + 1);
     var image3 = Math.floor((Math.random() * 5) + 1);

      $("#img1").attr("src",images[image1]);
      $("#img2").attr("src",images[image2]);
      $("#img3").attr("src",images[image3]);
  });