Img in header changing on each page load

5

I'm starting a new project in HTML5 and I would like to put a background img in the header, in vdd I want to put 4 images and I want them to change on every page refresh, I do not want a slider, site see an image and in each loading of the page img change. I'm starting the project now and have not done anything yet so I have no code to post. Does anyone know something similar?

    
asked by anonymous 21.11.2017 / 00:57

2 answers

4

If you use only JavaScript, I would suggest the following:

Rename background files with names with sequential numbers:

fundo1.jpg
fundo2.jpg
fundo3.jpg
fundo4.jpg

Then after your header , call the script:

<script>
var fundo = [1,2,3,4][Math.floor(Math.random()*4)];
var e_header = document.querySelector("header");
e_header.style.backgroundImage = "url(fundo"+fundo+".jpg)";
</script>

Note: Because images will be called by random numbers, it may be that the same image is loaded after a new page load. If avoiding this is of importance , you can create a localStorage to prevent the same image from being loaded again at the next page load. For this the code changes:

<script>
function randFundo(){
   var fundo = [1,2,3][Math.floor(Math.random()*3)];
   !localStorage.fundo ? localStorage.fundo = fundo : 0;
   return localStorage.fundo == fundo
   ?
   (localStorage.fundo = fundo+1)
   :
   (localStorage.fundo = fundo);
}

var e_header = document.querySelector("header");
e_header.style.backgroundImage = "url(fundo"+randFundo()+".jpg)";
</script>

SIMULATION

  

Code only for test without refresh on page. Use one of the codes   above.

In the example below, click the Refresh button to change the background of div :

var localstorage = { fundo: "" };
function atualizar(){
   var e_header = document.querySelector("header");
   e_header.style.backgroundImage = "url(http://dvdteste.hospedagemdesites.ws/imagem"+randFundo()+".jpg)";
}

function randFundo(){
   var fundo = [1,2,3][Math.floor(Math.random()*3)];
   !localstorage.fundo ? localstorage.fundo = fundo : 0;
   return localstorage.fundo == fundo
   ?
   (localstorage.fundo = fundo+1)
   :
   (localstorage.fundo = fundo);
}

window.onload = atualizar;
header{
   display: block;
   width: 300px;
   height: 200px;
   background-color: yellow;
   background-size: cover;
   float: left;
}
<header></header>
<input type="button" value="Atualizar" onclick="atualizar()" />
    
21.11.2017 / 01:53
1

It can be with PHP as well. Try it

Put this in PHP:

<?php
    $bg = array('bg-01.jpg', 'bg-02.jpg', 'bg-03.jpg', 'bg-04.jpg' );     
    $i = rand(0, count($bg)-1); 
    $selectedBg = "$bg[$i]"; 
?>

And this in css:

body{
    background: url(images/<?php echo $selectedBg; ?>);
}

Important, the name of the images should be "bg-0X.jpg" ok, if you want to add more imgs just put in the Array 'bg-05.jpg' and save the img in the folder.

[] 's

    
21.11.2017 / 01:36