user3004208 user3004208 - 3 months ago 136
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?

EDIT

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

However typing in the url

www.example.com/models.php/5
doesnt do anything.

Am i doing something wrong?

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

function goToSlide(number) {
$("#MyCarousel").carousel(number);
}

Answer

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.

.carousel(number)

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) {
   $("#carousel").carousel(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 www.example.com/models.php/4

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);
}
goToSlide(slide);