Adding Multiple Fading Images To A Background in WordPress

You can add multiple sliding/fading images to a background HTML element using the Backstretch jQuery plugin, this is great if you just want to alternate a number of images behind another web page element similar to a slider but without the overhead of using a slider plugin.

Image Preparation

Generally you’ll want to optimise your images for the most average viewable size, so for example if it’s full screen desktop you’ll need to get a width at least between 1200px to 16oopx at a decent compression, say jpeg level 7 in Photoshop, if the background images are more abstract in nature and the image is less defined you can probably get that jpeg compression down to a level 3 of 4.

Setting up Backstretch

Download the latest version and file the backstretch.min.js in your theme’s js folder, you’ll also want to create an initialise file for the jQuery plugin, called backstretch-init.js – then also move to your theme’s js folder.

The content of the backstretch-init.js file will apply the backstretch image effect to the element we are targeting, so in the code below…

jQuery(document).ready(function($) {
$(".header").backstretch([ // Target your HTML element
'/wp-content/uploads/2016/09/image-1.jpg', // Add in your images
duration:3000, // Time between transitions
fade:750, // Transition effect
view raw backstretch-init.js hosted with ❤ by GitHub

Loading the Scripts

Now these files will need to be enqueued for WordPress to load them, so add this in your functions.php file

<?php //<~ don't add me in
add_action( 'wp_enqueue_scripts', 'themeprefix_backstretch_background_scripts', );
* Backstretch for Custom Background Multiple Images
function themeprefix_backstretch_background_scripts() {
wp_enqueue_script( 'backstretch', get_stylesheet_directory_uri() . '/js/backstretch.min.js', array( 'jquery' ), '2.0.4', true );
wp_enqueue_script( 'backstretch-image', get_stylesheet_directory_uri().'/js/backstretch-init.js' , array( 'backstretch' ), '1.0.0', true );
view raw functions.php hosted with ❤ by GitHub

So here we are loading the backstretch files, when the initialise script backstretch-init.js is called it is calling for backstretch-min.js which in turn is calling for  jQuery.

That’s it, load in as many images as required and adjust the fade and duration values to suit.

Further ref and ref

Leave a Comment

%d bloggers like this: