Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

random background-image on page load

I'm trying to have my background image to chance every time a user visits the website. I found some code here on stackoverflow but I can't seem to get it to work.

What is wrong with this code?

CODE:

$(document).ready(function() {    
    var bgArray = ['A-VOLTE.jpg', 'AL-DI-LA.jpg', 'CON-TE.jpg', 'DAVIDE-E-GOLIA.jpg', 'DELLE-VERITA.jpg', 'DI-NOI.jpg', 'DIVIDERE.jpg', 'FA-NIENTE.jpg', 'FORSE.jpg', 'GRAZIE.jpg', 'IL-CONTATTO.jpg', 'IL-PONTE.jpg', 'IMPERATIVO.jpg', 'INDELEBILE.jpg', '-VOLONTA.jpg', 'MERITAVI.jpg', 'MUOVERE.jpg', 'NEL-DUBBIO.jpg', 'NESSUNO.jpg', 'NON-LO-SAI.jpg', 'PER-DIMENTICARE.jpg', 'PRIMA-DI-ANDARE.jpg', 'PROFONDO.jpg', 'SARA-SUO.jpg', 'SEMPRE.jpg', 'TUTTO-DA-RIFARE.jpg', 'TUTTO-PER-TE.jpg', 'UN-RICORDO.jpg', 'UNTITLED-1.jpg', 'UNTITLED-2.jpg', 'VERO.jpg', 'VIENI-CON-ME.jpg'];
    var bg = bgArray[Math.floor(Math.random() * bgArray.lenght)];
    // If you have defined a path for the images
    var path = 'artworks/abstract/';
    var imageUrl = path + bg;
    // then you can put it right before the variable 'bg'
    $('body').css('background-image', 'url(' + imageUrl +')');          
});


I get no alerts, no bg chance, no nothing. Thanks a lot for your help!
like image 775
valerio0999 Avatar asked Apr 16 '26 20:04

valerio0999


1 Answers

length is mispelled in var bg = bgArray[Math.floor(Math.random() * bgArray.lenght)];

Edit: Make sure to work with the javascript console, if that's not already the case. A simple log of imageUrl variable would have gave you a clue about the mistake.

like image 177
Michael P. Bazos Avatar answered Apr 18 '26 10:04

Michael P. Bazos