jqueryjquery-backstretch

jquery backstretch - jump to a particular image


I'm using the Backstretch jquery as a slideshow on a page. I'd like to be able to link to individual images on the page (from a blog post, or even from a thumbnail view, for example).

For example, I'd like to be able to go mysite.com/projects/firstproject#3 - and have it load the page as normal, but start on image 3 rather than at the beginning.

Here's my basic backstretch code:

var[images] = [ '/images/project1/1.jpg',
                '/images/project1/2.jpg',
                '/images/project1/3.jpg'
                '/images/project1/4.jpg'
                '/images/project1/5.jpg'
                ]

$(images).each(function() {
   $('<img/>')[0].src = this; 
});

var index = 0;

$.backstretch(images, {speed: 500});
$('body').data('backstretch').pause();

var identifier = window.location.hash.substring(1) - 1; 
  //this grabs the anchor at the end, and grabs it as "3" instead of "#3"
  //and I need to subtract 1, as backstretch expects the first image id to be 0. 

if (identifier > -1 )
    $('body').data('backstretch').show(identifier);
};

This works, but it doesn't work great. It shows the first image, loads the rest in the back, and then when it's complete, moves to the selected image. In a page with a bunch of images, this can be quite a delay.

Is there a faster/better way to do this?


Solution

  • Here's what mostly works. I set the backstretch area to be hidden by default. And then once backstretch has loaded the image I specified, it becomes visible again.

    CSS:

    <style>
        .backstretch {visibility:hidden;opacity:0}
        .backstretch.vis {visibility:visible;opacity:1}
    </style>
    

    Backstretch code:

    var identifier = window.location.hash.substring(1) - 1;
    
    if (identifier > 0) {
        $('body').backstretch(images, {speed: 500});
        $('body').data('backstretch').show(identifier);
        $('body').data('backstretch').pause();
    
        $(window).on("backstretch.after", function (e, identifier, index) {
            $('.backstretch').addClass('vis');
        });
    } else {    
        $('body').backstretch(images, {speed: 500});
        $('.backstretch').addClass('vis');
        $('body').data('backstretch').pause();
    };
    

    This, of course, is just a snippet. There's all the rest of the code (images, next/prev, etc) around that to make it work.