How to change background images randomly in JavaScript [with sample code]

この記事は約4分で読めます。

If you want to change background images randomly in your web site, here is the script for you.

Changing background image randomly in JavaScript

This JavaScript changes/switches four background images randomly every time loaded the page.

Please see the small movie below.

JS codes of randomly switching background images

Here is the source code with some explanations.

<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS">
  <meta http-equiv="Content-Script-Type" content="text/javascript">
  <title>Random Background</title>
<script type="text/javascript">

  function background(){
    var BG = Math.floor(Math.random() * 4);
//Math.random() creates random number.
//Math.floor() switches random number to its integer value.
// "Math.random() * 4"  means a random number generates between 0 to 3.

    if (BG == 0) {document.body.background = "image1.jpeg";}
    else if (BG == 1) {document.body.background = "image2.jpeg";}
    else if (BG == 2) {document.body.background = "image3.jpeg";}
    else {document.body.background = "image4.jpeg";}
//If generated random integer is 0, image1.jpeg will be displayed for background image. It it is 1,  image2.jpeg will be displayed.... and so on.

  }
</script>
</head>
<body background ="image1.jpeg" onload="background();">
  <h1>Ramdom change background</h1>
</body>
</html>

 

Related Article

[JS learning series] How to make slot machine by JavaScript
Let's  make three digits slot machine only with JavaScript.
How to make "Now Loading...." page on JavaScript
You might see "Now Loading...." page when you browse some websites. Let's make the "Now Loading... Wait for few secon...
JavaScript Learning Series - Web Landing Page with Flying balloons -

 

コメント

タイトルとURLをコピーしました