Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap carousel - link to specific slide

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

like image 595
Alex Green Avatar asked Feb 14 '26 23:02

Alex Green


1 Answers

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

like image 55
Schmalzy Avatar answered Feb 16 '26 12:02

Schmalzy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!