Dev1997
Dev1997

Reputation: 677

BxSlider: Save position of slider when page is refreshed/changed

This is a tricky one and I'm not sure on how to go about this.

I'm using BxSlider for a website which will slide through images like a normal typical slider. The problem is that I need a way to save the last position of the slider the user was on so that when they refresh or navigate to a different page on the site, it does not reset back to the first slide.

Picture example of what I mean:

Position of slider enter image description here

Picture (1) : The current position of the slider.

Picture (2): The position of the slider after refresh or page change.

I need the slider to continue from the last slide rather than resetting back to the first slide.

Here is an example JsFiddle of the slider as well as the HTML:

<ul class="bxslider">
<li><img src="http://bxslider.com/images/730_200/hill_trees.jpg" /></li>
<li><img src="http://bxslider.com/images/730_200/me_trees.jpg" /></li>
<li><img src="http://bxslider.com/images/730_200/houses.jpg" /></li>
<li><img src="http://bxslider.com/images/730_200/tree_root.jpg" /></li>
<li><img src="http://bxslider.com/images/730_200/hill_fence.jpg" /></li>
<li><img src="http://bxslider.com/images/730_200/trees.jpg" /></li>

Any idea's will be greatly appreciated.

Upvotes: 1

Views: 924

Answers (1)

theblindprophet
theblindprophet

Reputation: 7937

There are two options that bxSlider offer: startSlide and onSlideAfter

You can look at their documentation here: Docs

Then what you need to do it every time the slide changes you can store the current index using localStorage.setItem() and when the page is loaded you can retrieve the current index using localStorage.getItem().

JS:

$(document).ready(function() {

    var startIndex = localStorage.getItem("currentIndex");
    if(startIndex == null)
        startIndex = 0;

    $('.bxslider').bxSlider({
    startSlide: startIndex,
        mode: 'horizontal',
        infiniteLoop: true,
        auto: true,
        autoStart: true,
        autoDirection: 'next',
        autoHover: true,
        pause: 3000,
        autoControls: false,
        pager: true,
        pagerType: 'full',
        controls: true,
        captions: true,
        speed: 500,
        onSlideAfter: function($slideElm, oldIndex, newIndex) {save($slideElm, oldIndex, newIndex)}
});

    function save($slideElm, oldIndex, newIndex) {
        console.log(oldIndex + " " + newIndex);

        localStorage.setItem("currentIndex", newIndex);
    }
})

Fiddle: http://jsfiddle.net/Yq3RM/1264/

Upvotes: 1

Related Questions