2

I have found a lot of help on displaying the current slide number in the html and linking to a particular slide on the current page but my question is a little different...

I need to be able to link to a particular slide in the carousel in another page. So I will have something like: a href="page2.html#slide2" on 'index.html'

When the user clicks this link, it takes them to the 'page2.html' page and with the second slide displayed.

Any help is appreciated. Thanks, Alex

Alex Green
  • 70
  • 1
  • 6
  • You'll need to store the index of the slide in the url so for slide2 the index would be `1`. Then when you load the page you need to grab the index from the url and then call `$('#myCarousel').carousel(index);` – Trevor Nov 27 '13 at 18:18

2 Answers2

5

You can use a query string like... www.example.com?slide=2

$(document).ready(function(){

    function getParameterByName(name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
        return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }

    $('#myCarousel').carousel(getParameterByName('slide'));
});

Or hash values like... www.example.com#2

$(document).ready(function(){
    $('#myCarousel').carousel(window.location.hash.substring(1));
});

Which ever you use, you have to only extract an integer from the url, so you may want to make the code a little more robust to ensure you are only moving the carousel if you get a valid integer and also check that it is within the bounds of the number of slides that exist within the carousel.

.carousel(number)

Cycles the carousel to a particular frame (0 based, similar to an array).

Schmalzy
  • 17,044
  • 7
  • 46
  • 47
  • what would you add to the carousel to achieve this? – Max Rose-Collins Nov 29 '13 at 10:22
  • 1
    Just a note that `carousel` expects an integer and `getParameterByName()` will always return a string. This will cause problems so you should look into casting or using @cdonner's solution below. – KyleMit Oct 07 '14 at 13:52
4

New and improved version tests for a valid integer and defaults to 0:

function qs(key) {
    key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
    var match = location.search.match(new RegExp("[?&]" + key + "=([^&]+)(&|$)"));
    var slide = match && decodeURIComponent(match[1].replace(/\+/g, " "));
    if (Math.floor(slide) == slide && $.isNumeric(slide))
        return parseInt(slide);
    else
        return 0;
}
$('#myCarousel').carousel(qs('slide'));

Credits go to this and this question.

Community
  • 1
  • 1
cdonner
  • 37,019
  • 22
  • 105
  • 153
  • Is there a way to update the url when the slide changes by using the carousel controls? For example, to go from www.webpage.com?=slide1 to www.webpage.com?=slide2 ? – MikeMichaels Aug 27 '19 at 17:14