Random body background image

I have tried several tutorials online and no one seems to be working properly. I just try to do this:

I have 9 different .jpg images that I need to randomly display on the page load - to be the background. Should it be pretty simple?

Thanks,

EDIT (Sorry, forgot to attach the code - find on the Internet):

$(document).ready(function(){ bgImageTotal=9; randomNumber = Math.round(Math.random()*(bgImageTotal-1))+1; imgPath=('../img/bg/'+randomNumber+'.jpg'); $('body').css('background-image', ('url("'+imgPath+'")')); }); 
+6
source share
2 answers

Check out this tutorial: http://briancray.com/2009/12/28/simple-image-randomizer-jquery/

First create an array of images:

 var images = ['image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg', 'image5.jpg']; 

Then set the random image as the background image:

 $('body').css({'background-image': 'url(images/' + images[Math.floor(Math.random() * images.length)] + ')'}); 

This should not work.

+22
source

using jQuery: $("body").css("background-image", "url(" + Math.floor(Math.random()*9) + ".jpg)");

This assumes your images are named 0.jpg to 8.jpg and are in the same directory as your page.

0
source

Source: https://habr.com/ru/post/905764/


All Articles