I am trying to call backstretch.js dynamically in a WordPress template. I'm using Advanced Custom Fields with a repeater field to set the images and CSS classes for each section.
I build the array in PHP, and localise it using wp_localize_script();
The JS object looks like this:
Object
images : Object
bkClass : Array[2]
0 : "table"
1 : "lounge"
bkImage : Array[2]
0 : "http://web.dev/wp-content/uploads/2017/02/table.jpg"
1 : "http://web.dev/wp-content/uploads/2017/02/lounge.jpg"
And the backstretch call looks like this:
// Finds the <div> class and applies the correct image.
jQuery(document).ready(function($) {
$(images).each(function(){
$("." + this.images.bkClass).backstretch(this.images.bkImage);
});
});
I've checked the HTML output and it is correct. But the images are being applied to the same div, and the image is flickering between the two.
If I manually call backstretch it works:
<script>
jQuery(document).ready(function ($) {
$(".table").backstretch("http://web.dev/wp-content/uploads/2017/02/table.jpg");
$(".lounge").backstretch("http://web.dev/wp-content/uploads/2017/02/lounge.jpg");
});
</script>
Not quite sure where I'm going wrong. Would be grateful is someone could help me out here.
Try to use on window load instead of document ready as window load event occurs later, when all content (e.g. images) also has been loaded.
And if that doesn't work try it as:
Javascript
HTML