Random backgrounds in each page load on static pages

0

I'm creating a website / blog with jekyll, and I created a banner.html and it includes it in the default layout, but I wanted to load the page every time it was a different background in this banner and I'm trying to do this by javascript but I have not yet been successful, the code I created was this:

function aplicarBGAleatorio() {
var numeroBG = Math.floor(Math.random() * 5);

if ($("#bannerMain").length) {
    alert(backgroundAleatorio(numeroBG));
    $("#bannerMain").css({ 'background-image': 'url("../../assets/Imagens/' + backgroundAleatorio(numeroBG) + '");' });
}

if ($("#bannerSecondary").length) {
    alert(backgroundAleatorio(numeroBG));
    $("#bannerSecondary").css({ 'background-image': 'url("../../assets/Imagens/' + backgroundAleatorio(numeroBG) + '");' });
}
}

function backgroundAleatorio(x) {
switch (x) {
    case 0:
        return "background0.jpg";
        break;
    case 1:
        return "background1.jpg";
        break;
    case 2:
        return "background2.jpg";
        break;
    case 3:
        return "background3.jpg";
        break;
    case 4:
        return "background4.jpg";
        break;
}
}

$(document).ready(function () {

aplicarBGAleatorio();

With this code the way it is, the two alerts inside the ifs work, but the backgrounds do not appear, not the error in the console.

<section id="bannerMain" data-speed="3">
<main>
    <h1>{% if page.title %}{{ page.title | escape }}{% else %}{{ site.title | escape }}{% endif %}</h1>
    <hr>
    <h2>{% if page.desc %}{{ page.desc | escape }}{% else %}{{ site.slogan | escape }}{% endif %}</h2>
    <button>{ Ver mais }</button>
</main>

section#bannerMain {
width: 100%;
height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background-repeat: no-repeat;
background-position: 50% 0;
background-attachment: fixed;
background-size: cover;
padding-top: 75px;

}

    
asked by anonymous 13.07.2017 / 17:46

1 answer

1

Modify the lines below:

Ao invés de fazer:

$("#bannerMain").css({ 'background-image': 'url("../../assets/Imagens/' + backgroundAleatorio(numeroBG) + '");' });


$("#bannerSecondary").css({ 'background-image': 'url("../../assets/Imagens/' + backgroundAleatorio(numeroBG) + '");' });

Faça:

$('#bannerMain').css('background-image', 'url("../../assets/Imagens/' + backgroundAleatorio(numeroBG) + '")');

$('#bannerSecondary').css('background-image', 'url("../../assets/Imagens/' + backgroundAleatorio(numeroBG) + '")');
    
13.07.2017 / 18:32