I am currently using OwlCarousel2 for my carousel needs. I chose OwlCarousel2 over OwlCarousel1 since it has an URL hash navigation: http://www.owlcarousel.owlgraphic.com/demos/urlhashnav.html
<div id="contestant-carousel">
<div id="poll-images" class="owl-carousel">
<?php
for($counter = 1; $counter <= 14; $counter++) {
echo "<div class='item' data-hash='$counter'><a href='" . HTTP_SERVER . "vote.php?contestant_id=$counter'><img src='/images/contestants_mobile/$counter.png' alt='$counter'></a></div>";
}
?>
</div>
</div>
Above is the PHP code I use to generate my carousel. I have fourteen images, so my code loops through all fourteen images and adds a data-hash
object to each image (for the anchor navigating needs).
The following is my Javascript code:
$(document).ready(function() {
$("#poll-images").owlCarousel({
items: 1,
loop:false,
center:true,
margin:10,
lazyLoad:false,
URLhashListener:true,
onDragged:callback,
autoplayHoverPause:true,
startPosition: 'URLHash'
});
function callback(event) {
window.location.hash = event.item.index;
console.log(event.item.index);
}
});
Now, the above carousel works perfectly if the user manually adds in the hash in their URL, i.e. someurl.com/voting.php#4
, this would navigate to the fourth image.
However, want I want to do is, if the url navigates to someurl.com/voting.php
, as they scroll through each image, my URL would update its anchor accordingly. Why? Since if my user clicks on the image (which contains a href
), and they go to the previous page, they could navigate back to the image they were looking at, instead of the default behavior of going to the first image.
According to the OwlCarousel2 API (which is actually quite different from OwlCarousel1), to get the current item, you can do this:
function callback(event) {
// Provided by the core
var element = event.target; // DOM element, in this example .owl-carousel
var name = event.type; // Name of the event, in this example dragged
var namespace = event.namespace; // Namespace of the event, in this example owl.carousel
var items = event.item.count; // Number of items
var item = event.item.index; // Position of the current item
// Provided by the navigation plugin
var pages = event.page.count; // Number of pages
var page = event.page.index; // Position of the current page
var size = event.page.size; // Number of items per page }
Specifically, using event.item.index
. My code did precisely that! But I am unable to retrieve the current index! My error is: Uncaught TypeError: Cannot read property 'item' of undefined
under Chrome's console.
Any help from JS gurus would be much appreciated!
I tried searching all over StackOverflow as well as the OwlCarousel2 API to see if I could do this, however, no luck.
I have also checked this thread: append /remove anchor name from current url without refresh