Search code examples
jqueryjquery-backstretch

.destroy (backstretch) doesn't work with ajax content


I've a website with one instance of backstretch for a slider (in div #backstretch), loaded from an array of images on the site itself. The array looks like this:

<script>
$('#backstretch').backstretch([
[
{ width: 1400, url: "./img/05_1400.jpg" },
{ width: 1000, url: "./img/05_1000.jpg" },
{ width: 780, url: "./img/05_780.jpg" },
{ width: 500, url: "./img/05_500.jpg" }
],
[
{ width: 1400, url: "./img/02_1400.jpg" },
{ width: 1000, url: "./img/02_1000.jpg" },
{ width: 780, url: "./img/02_780.jpg" },
{ width: 500, url: "./img/02_500.jpg" }
]
], {
fade: 2000,
duration: 5000
});
</script>

To change the set of images of this slider on click, I load new content in my website with jquery .load(). The new content has also an array with new images. To initiate the load there are some divs with class .item below the slider to click on to start load the new set of images. By clicking on one item the url here is dynamically set up with the index of items.

jQuery(function(){
$(document).on("click", '.item', function(index, element) {
var index = $('.item').index(this);
var singleurl = 'single_' + index + '.html';
var $instance = $('#backstretch').data('backstretch');
$instance.destroy('preserveBackground');
$('#singleview').fadeIn(1500).load(singleurl);    
});

The problem is, that the first time I change the set of images it works fine. The old set is destroyed and the new set is sliding. But if I cklick on the next item to load the next image set the old images and the images of the first set appearing in the slidshow too. They are not realy destroyed. How ca I fix it?


Solution

  • So I get it work now, with help from the maintainer of backstretch.

    jQuery(function(e) {
    $(document).on("click", '.inneritem', function(index, element) {
    var indexe = $('.inneritem').index(this);  // count items
    var singleurl = 'single_' + indexe + '.html';  // create url for each item
    $('html').animate({scrollTop: '0px'}, 1200).promise().then(function() {     // scroll to top
    var $instance = $('#backstretch').data('backstretch');  // get the instance
    $instance && $instance.destroy(true);  // destroy it
    $('#singleview').fadeIn().load(singleurl);   // load new backstretch slides
    });
    });
    });
    

    The goal is to put the call and destroying the instance at the right place. In the code of my question was some code missing to keep it simpler, but this code was the majorproblem:

    $('html, body').animate({scrollTop: '0px'}, 1200, function() {
    $('#singleview').fadeIn().load(singleurl);
    

    I wanted to scroll top before loading the content an called backstretch twice ('html, body'). I didn't see that before. .promise().then( was added. Now it works like a charm.