user3004208 user3004208 - 1 year ago 290
Javascript Question

twitter bootstrap carousel link directly to a specific slide

I am using twitter bootstrap carousel on my website to display a set of images. i am wondering if it is possible to allow a link to link to a specific slide in the carousel. So out of 10 slides a user can click a link to go directly to say slide 5 from a href link.

Is this possible with bootstrap carousel or am i barking up the wrong tree?


Hi, so i have added the following to my javascript under document.ready function.

However typing in the url
doesnt do anything.

Am i doing something wrong?

var url = window.location.href;
var slide = url.substring(url.lastIndexOf('/')+1); // 4

function goToSlide(number) {

Answer Source

The JavaScript-free way

You can use data-slide-to attribute for this, which accepts 0-based indexes represents the slide number.

Use data attributes to easily control the position of the carousel. data-slide accepts the keywords prev or next, which alters the slide position relative to its current position. Alternatively, use data-slide-to to pass a raw slide index to the carousel data-slide-to="2", which shifts the slide position to a particular index beginning with 0.

Just add an attribute to your anchor, and off you go.

<a href="#" data-slide-to="5">Go to slide #5</a>

Thanks to Cawas's comment on this answer and Jonas's answer on this question.

The old-school JavaScript way

You need to use the .carousel(number) function.


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

Check out the bootstrap docs.

To be more specific;

Create a javascript function to call, it should look like this :

function goToSlide(number) {

And then, just add an onClick event on your link.

<a href="#" onClick="javascript:goToSlide(5);">Go to slide #5</a>

Getting the slide info from the URL

The source link is

You could check the url on document.ready, and if there's some data at the end of the url, you simply invoke your goToSlide function.

var url = window.location.href;
var slide = url.substring(url.lastIndexOf('/')+1); // 4

// Remove the trailing slash if necessary
if( slide.indexOf("/") > -1 ) { 
    var slideRmvSlash = slide.replace('/','');
    slide = parseInt(slideRmvSlash);