I'm very new to coding, so apologies if my terminology is inaccurate. I built a site with a bootstrap carousel. I wanted the caption to display in a separate column. I found this nifty code to do that:
$('.carousel').carousel();
var caption = $('div.item:nth-child(1) .carousel-caption');
$('#right').html(caption.html());
caption.css('display','none');
$(".carousel").on('slide.bs.carousel', function(evt) {
var caption = $('div.item:nth-child(' + ($(evt.relatedTarget).index()+1) + ') .carousel-caption');
$('#right').html(caption.html());
caption.css('display','none');
});
Thanks to folks here for the code: How to place Bootstrap Carousel image captions outside the carousel div?
I then display the caption in the location I want with a simple:
<p id="right"></p>
My issue is that I'm also appending a #hash to the URL so that I can target specific items in the carousel from other pages on my site (e.g, item four has the url www.mysite.com#4 so that I can link to that specific item). The code that appends the hash also sets the item as active. For reference, it is here:
$(document).ready(function() {
var url = document.location.toString();
var totalItems = $('.item').length;
//Initiate carousel
$('.carousel').carousel({
interval: false
})
$('.carousel').on('slid.bs.carousel', function () {
var currentIndex = $('div.active').index() + 1;
//Update pager-text
$('.pager-text').text(''+currentIndex+'/'+totalItems+'');
// Update location based on slide (index is 0-based)
window.location.hash = "#"+ parseInt($('.carousel .carousel-inner .item.active').index()+1);
});
if (url.match('#')) {
// Clear active item
$('.carousel .carousel-inner .item.active').removeClass('active');
// Activate item number #hash
$('.carousel-inner div:nth-child(' + url.split('#')[1] + ')').addClass('active');
//Update pager-text
$('.pager-text').text(''+url.split('#')[1]+'/'+totalItems+'');
}
});
h/t here: Update the current number of slide when jumping to specific item - Bootstrap 3 Carousel
However, the caption always matches the first item in the carousel list (which is the only one that has class="item active" in the html, otherwise the carousel will not display). How do I get the page to display the caption for the specific URL hash I want to target? For example, if I want it to match the caption for the carousel item at: www.myurl.com#4
Thank you! I'm happy to share all the code in github once it's done so others can use this.