Solution: Randomizing Background Images using Javascript

New Member
2 0 0

Hello all. I just wanted to share something I worked up to solve a need for random background images on the home page of a site I'm working on. (I'll post the URL of the site when we launch).

 

I was unable to find a workaround or get assistance from Shopify regarding the fact the Liquid appears to cache it's output so when you try to randomize a number it hangs on to the number it first outputs until you clear your cache and hard refresh. (Note: I'm open to any and all recommendations about how to work around this or how to streamline what I've done here. I'm really happy with how it works now and hopefully, it will help some of you out there too. 

 

Here's where I landed:

I have a section file specifically for the home page, where the user can add 1-12 background images through the Shopify backend. I ended up using Javascript to randomize because it doesn't cache the result. 

 

This took me far longer than I had anticipated so I wanted to share. 

Here is the code for the whole 'sections/home-background_images.liquid' file:

 

<!-- Home Page: Background Images -->

{% assign images = section.blocks.size %}
{% assign image_count = 1 %}

<script>

$(document).ready(function(){

	// Use Javascript to generate random number
	var rand = Math.floor((Math.random() * {{images}}) + 1);

	// Store total number of images from Liquid as a jQuery variable
	var total_image = {{ images | json }};

	// Loop through the blocks using Liquid
	{% for block in section.blocks %}

			// Start a jQuery counter that syncs with the Liquid counter
			var image_jCount = {{image_count}};

			// Store the current image file URL for use
			var img{{ image_count | json }} = '{{ block.settings.home-bg-imgs | img_url: 'master' }}';

			// Check the random number against the current counter in the loop
			if(rand == {{ image_count | json }}){
				// Set background image if the numbers match
				$('.home-bg-image').css('background-image', 'url("' + img{{ image_count | json }} + '")');
			}

				// Increment the Liquid counter to keep things moving
			{% assign image_count = image_count | plus: 1 %}

	{% endfor %}

});


</script>




{% schema %}

{
		"name": "Home Background Images",

		"blocks": [
		{
			"type": "bg-images",
			"name": "Home Background Images",
			"limit": 12,
			"settings": [
				{
					"type":      "image_picker",
					"id":        "home-bg-imgs",
					"label":     "Home BG Images"
				}
			]
		}
	]


}


{% endschema %}

{% stylesheet %}
{% endstylesheet %}

{% javascript %}
{% endjavascript %}
0 Likes
Shopify Partner
1663 50 173

Javascript is how you want to handle any type of template randomization.

All other ways are just funky hacks like just putting the random seed in the url, which means it's not really random either.

 

 

Problem Solved? ✔️Accept the solution so you can help others.
Confused? Busy? ? Get me to solve it paull.newton+shopifyforum@gmail.com.
Buy me a coffee? ☕ paypal.me/paulnewton or donate to eff.org
0 Likes
New Member
5 0 0

Can you give a little more info as to how you got this implemented? I need to add a random background image to my theme as well.

0 Likes
New Member
2 0 0

l will certainly try...

 

Once you have your Background Image schema set up you are able to retrieve the block settings 'size' which is the total number of images that have been added to your page. 

 

You use that number to randomize a number between 1 and the total number of images. Then you use the number selected to output that image as your background. 

 

The code I provided should work well if you want to try it. The images are added in the Shopify Admin when you go into customize/edit your homepage. 

 

Sorry I don't have the bandwidth right not to into greater detail just remember that you can weave Liquid code into Javascript functions. That was the thing that stumped me for awhile while sorting this out.

0 Likes
New Member
5 0 0

thanks for the response. yeah I implemented your code and it works through the Admin page, i just can't figure out how to display the uploaded images once they are in.

0 Likes
Highlighted
New Member
5 0 0

I figured this out, I finally realized that jquery was not installed in my theme. added it and voila, this works! thanks for writing this Ian. works great.

0 Likes