Multiple Background Images on Refresh

Working with Shopify, I found this bit of code, and was able to setup auto-switching full screen background images. You can use this to setup multiple background images that will change over automagically on page load. This comes in handy when working with Shopify when there are no page IDs, or template identifiers, and standard plugins are not available. Add the class of .bg to the Body element, and place the function in a script tag in the, or within it’s own php file, and link to it within the header.

function changeImg(imgNumber) { 	

     var myImages = ["{{ 'image1.jpg' | asset_url }}", "{{ 'image2.jpg' | asset_url }}", "{{ 'image3.jpg' | asset_url }}"];  	

     var imgShown = document.body.style.backgroundImage; 	

     var newImgNumber =Math.floor(Math.random()*myImages.length); 	

document.body.style.backgroundImage = 'url('+myImages[newImgNumber]+')'; 

} 

window.onload=changeImg;

 

.bg {   

    background-attachment:fixed;    

    background-repeat: no-repeat;    

    background-position:top right; 

}

 

Leave a Reply

katherine as a flat graphic icon

About Me

I’m an African / Ojibwe First Nations Web Developer living in Winnipeg, Manitoba.

Visit the Tips and Blog to see what I’m working on.