Rob
Rob

Reputation: 571

Dynamically call backstretch.js

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.

Upvotes: 0

Views: 197

Answers (1)

Aishan
Aishan

Reputation: 111

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

jQuery(window).load(function ($) {
  var images = [];

  // iterate over your selection
  $('#background img').each(function () {
    // save source to list
    images.push(this.src);
  });

// use plugin
$.backstretch(images, {duration: 3000, fade: 750});
});

HTML

<div id="background">
  <img src="http://web.dev/wp-content/uploads/2017/02/table.jpg" />
  <img src="http://web.dev/wp-content/uploads/2017/02/lounge.jpg" />
</div>

Upvotes: 0

Related Questions