-1

I want a full background changing randomly each time the page is refresh. My page is in HTML with CSS and JS (JQuery included). I've already tried a lot of solution from this website and many others, their is a lot of tutorials I know. But I think I'm doing something wrong because nothing function.

   <!DOCTYPE html>
   <html lang="fr">
     <head>
       <meta charset="UTF-8">
       <meta http-equiv="X-UA-Compatible" content="IE=edge">
       <meta name="viewport" content="width=device-width, initial-scale=1">
       <title>index</title>
       <script src="js/jquery-3.3.1.min.js"></script>
       <script src="js/popper.min.js"></script> 
       <script src="js/bootstrap-4.3.1.js"></script>

       <!-- Bootstrap -->
       <link href="css/bootstrap-4.3.1.css" rel="stylesheet">
       <style type="text/css">
       body {
    background: url(images/BG/bg01.jpg) no-repeat center center fixed; 
     -webkit-background-size: cover;
     -moz-background-size: cover;
     -o-background-size: cover;
     background-size: cover;
   }
       a:link {
       color: #000000;
   }
   a:hover {
       color: #000000;
   }
       </style>

I've got 13 backgrounds in the same folder named, bg01.jpg bg02.jpg bg03.jpg ... I don't understand how replace my url in the css part I had, where add the JS etc... Noobie topic, I'm sorry for it but I found no tuto who worked for me

enrico56
  • 13
  • 1

1 Answers1

1

You can use plain JavaScript for this purpose. Just generate a random number and set the background.

function randomBackground(){
    var num = Math.floor(Math.random() * 13) + 1; // will generate a random number between 0 and 12
    if(num.toString().length == 1) num = "0" + num;
    document.body.style.background = "url('images/BG/bg"+num+".jpg')"; // for images: bg01.jpg, bg02.jpg, bg03.jpg, ... bg13.jpg
    document.body.style.backgroundPosition = "center";
    document.body.style.backgroundRepeat = "no-repeat";
    document.body.style.backgroundSize = "cover";
}
N3R4ZZuRR0
  • 2,400
  • 4
  • 18
  • 32
  • The OP has 13 different images... `'0'+(num+1)` won't work in this case (it'll produce, e.g. `011`) – FZs Sep 30 '19 at 16:27
  • 1
    Oh I missed that, have edited my answer. – N3R4ZZuRR0 Sep 30 '19 at 16:30
  • Ok tank you,so I include it in the header betweean `````` but I don't get how I use it in my css part of code, should I replace my ``` body { background: url() ``` by ``` body { randomBackground () ``` ? – enrico56 Sep 30 '19 at 17:18
  • Because at the moment I only get a blank page... I don't get it – enrico56 Sep 30 '19 at 17:21
  • You can change your body tag like this: `` – N3R4ZZuRR0 Oct 01 '19 at 02:05
  • 1
    Thank you very much !! Now it's loading my background, but it lost all my css values of cover etc... so it doesn't fit and it isn't "responsive" – enrico56 Oct 01 '19 at 07:32