0
I’m creating a site/blog with Jekyll, and I created a banner.html and includes it in the default layout, but I wanted to make loading the page all the time a different background on this banner and I’m trying to do it by javascript but I haven’t had any success yet, the code you 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, both Alerts inside ifs work, but backgrounds do not appear, and not from 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;
}
Have you looked at the browser inspector what is the value of the property that was loaded? By the way, "do not appear" is the background turn white, without any image?
– Woss
Does the browser show an error? if yes which?
– Bsalvo
Make html,css available so we can analyze the whole context..
– Bsalvo
Make html and css available
– Gabriel Carvalho
@Andersoncarloswoss in Chrome inspector does not give clues that some background-image has been applied, the background turns white, no picture without error in the console and with nothing different in inspector
– Daniel Santos
The path of
URL
of the images is incorrect.– FabianoLothor
@Fabianolothor but I did some tests leaving javascript aside and putting that same url
url("../../assets/Imagens/background0.jpg");
in css it appears the background– Daniel Santos