1

I want to make a website that the user will decide something. The user will click what he or she chose.

I want to know how to make the picture change to a random other picture everytime the user clicks it.

Is there any way to do that?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Hyper Lord
  • 13
  • 1
  • 6
  • http://stackoverflow.com/help/how-to-ask – Blazemonger Apr 30 '15 at 13:44
  • I've posted an answer up for you to explain the general concept. However, if you've already started on your website and want a particular answer designed directly around the code you're using, post it up for us and we can "tailor" you a more direct response. – Fata1Err0r Apr 30 '15 at 13:50

3 Answers3

1

This should give you the type of effect you want. Basically you're storing your images in an array, then you're going to randomly pick an index, then display it.

var yourImages = ["image1.png","image2.png","image3.png"];

var randomImage = Math.round(Math.random()*yourImages.length);
function displayImage()
{
document.write(yourImages[randomImage]);
}

Here is an example that's more geared toward what you asked, after I read your question again. If the user clicks on the image, it'll change to a random one.

JS:

<img id="currentImage" src="defaultImage.png" onclick="changePicture()">

<script>
  function changePicture(){
   var yourImages = ["image1.png","image2.png","image3.png"];
   var randomImage = Math.round(Math.random()*yourImages.length);
   var setImg = document.getElementById("currentImage").src;
   setImg = yourImages[randomImage];
  }
</script>

jQuery:

<img id="currentImage" src="defaultImage.png">

<script>
 $("#currentImage").click(function(){
    var yourImages = ["image1.png","image2.png","image3.png"];
    var randomImage = Math.round(Math.random()*yourImages.length);
    $("#currentImage").attr("src", yourImages[randomImage]);

});
</script>
Fata1Err0r
  • 836
  • 1
  • 6
  • 14
1

create an array with all the urls of the images you wanna use. e.g.

HTML:

<img id='the-image-to-change'/>

JS:

var imageUrls = [
 'http://placehold.it/255x255&text=A',
 'http://placehold.it/255x255&text=B',
// ... more
  'http://placehold.it/255x255&text=Z'
];

if you're not using jQuery:

var img = document.getElementById('the-image-to-change');
img.addEventListener("click", function() {
    this.src = imageUrls[Math.floor(Math.random() * imageUrls.length)];
});

if jQuery (has not been tested)

img = $('#the-image-to-change');
img.on('click', function() {
    this.src = imageUrls[Math.floor(Math.random() * imageUrls.length)];
});
Mace
  • 38
  • 5
0

Create an array of your picture, and use

Math.random();

To select a random index from your picture array that will be shown??

yahya el fakir
  • 562
  • 2
  • 12