Eric Rösch Eric Rösch - 2 months ago 14
CSS Question

Randomize background image using button onClick event

I want to randomize the background image when the user clicks a button.

Here's what I have.

Every time the button at the bottom right is cliked, I want to randomize the background image from a set array of externally hosted images.

How can I achieve that? (Without PHP, if possible.)

Answer

Try this method:

<script type="text/javascript">
    function randomImg1() {
      var myImages1 = new Array ();
      myImages1[1] = "img/who/1.jpg";
      myImages1[2] = "img/who/2.jpg";
      myImages1[3] = "img/who/3.jpg";
      var rnd = Math.floor( Math.random() * myImages1.length );
      if( rnd == 0 ) {
        rnd =1;
      }
      html_code = '<img class="who" src="' + myImages1[rnd] + '" />";
      document.write(html_code);
    }
</script>

You can also check out this

// EDIT -- By Pipskweak

instead of

html_code = '<img class="who" src="' + myImages1[rnd] + '" />";
document.write(html_code);

we could do this;

document.getElementsByTagName("body")[0].setAttribute('style','background-image: url(' + myImages1[rnd] + ')');

after all, background image was mentioned.