-3

How I can have background images changing each time someone visits a homepage? The current background image is controlled in the CSS, not HTML so any help would be greatly appreciated.

See CSS for the single background image:

 header .container-fluid
 {
 background-image: url("../../images/The Connection at St-Martin-in-the- 
 Fields/Carousel image - med res The Connection -1067838.jpg");
 background-repeat: no-repeat;
 background-size: cover;
 height: 100vh;
 padding-top: 36px;
 }
Just Joel
  • 37
  • 2
  • 9

1 Answers1

0

Just add a little JavaScript to your page to change the image on page load:

// make a list of images to select from
var images = ['cat.jpg', 'dog.jpg'];

// find the element whose background image you want to change
var elem = document.querySelector('header .container-fluid');

// get the index position of the image in `images` to be displayed
var index = Math.floor(Math.random() * images.length);

// set the background image property
elem.style.backgroundImage = 'url(' + images[index] + ')';

The background image set by JavaScript will have priority over the CSS style, so the image set by JavaScript will be displayed.

duhaime
  • 25,611
  • 17
  • 169
  • 224
  • floor function is more appropriate than parseInt – Temani Afif Apr 11 '18 at 22:46
  • @duhaime thanks for this, I tried adding it but nothing seems to change when I place my own images in the relevant areas of the code – Just Joel Apr 11 '18 at 22:56
  • @JustJoel make sure you post the code above between ``, and make sure you place that full script block as the last block before `

    ` on your page. So the end of your HTML document should look like `

    – duhaime Apr 11 '18 at 23:07
  • Thanks for that, one last thing, how would i change the image directory on the js code? – Just Joel Apr 12 '18 at 20:50
  • @JustJoel the easiest way to proceed is to make your images available to your server. So if you're hosting on `http://localhost:5000` and that server is running in `C:\App`, add your images to `C:\App\images`. Then you should be able to define your image list like `var images = ["images/cat.jpg", "images/dog.jpg"];` I hope that helps! – duhaime Apr 12 '18 at 21:55