KyleD KyleD - 1 year ago 125
Javascript Question

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="" /></li>
<li><img src="" /></li>
<li><img src="" /></li>
<li><img src="" /></li>
<li><img src="" /></li>
<li><img src="" /></li>

Any idea's will be greatly appreciated.

Answer Source

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().


$(document).ready(function() {

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

    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);


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download