Search code examples
javascripthtmlbxslider

Real connection between bxslider and the url


Is it possible get a real connection between bxslider and the url like the following examples?

www.domain.com/#slide-01
www.domain.com/#slide-02
www.domain.com/#slide-03

The url should update if the user change the slide and it also would be nice to drive bxslider by the url + #Anchor. If the user type www.domain.com/#slide-02 it should display the second slide.

<div class="bxslider-images">
      <div id="slide-01"><img src="image_01.jpg" border="0"></div>
      <div id="slide-02"><img src="image_02.jpg" border="0"></div>
      <div id="slide-03"><img src="image_03.jpg" border="0"></div>
</div>

Edit: With the help of baao the slider is now driven by the id's of the slides, but sadly it is out of sync, even though the URL is correct now, it skipps the 2nd slide.

$(document).ready(function(){

    var sliderImages = $('.bxslider-images').bxSlider({

        pager:false,
        startSlide: 0,
        infiniteLoop: false,
        onSlideNext: doThis,
        onSlidePrev: doThis,

    });

    function doThis(element, old, newslide){
        var urlWithoutAnchor = document.URL.replace(/#.*$/, "");
        var newUrl = urlWithoutAnchor + '#' + element.attr('id');
        console.log(newUrl);
        window.location = newUrl;
        sliderImages.goToSlide(newslide);

    }

});

Any help would be appreciated.


Solution

  • You can do this with this code:

    var url = window.location.href;
    if (url == 'http://www.domain.com/') // or whatever it is
    {
    window.location.href = url + '#slide-01'; // etc...
    }
    

    within your slide function!

    EDIT:

    I don't use bxslider, so I'm not 100% sure if this will work, but it might fit your needs:

    $(document).ready(function(){
    
    
    var url = window.location.href;
    
    var slide = url.split('#');
        if (slide[1]) {
    
    
    var slidenumber = slide[1].replace(/([a-z,0,/-])/g, '');
        }
    
    if (!slidenumber) { slidenumber = 0;}
    
    
    var sliderContent = $('.bxslider').bxSlider({
         pager:false,
         startSlide: slidenumber,
         var urlWithoutAnchor = document.URL.replace(/#.*$/, "");
         //location.hash.replace('#','')
         window.location.href = urlWithoutAnchor + '#' + newslide;
    });
    
    });