I'm trying to implement a carousel with Javascript but I'm having trouble with my navigation buttons.
Prev and Next works fine but the navigation dots as I'm calling are not.
Also, I want to show the title of the images on a span as per the HTML on jsfiddle. You can see my attempt on the javascript file bellow the following comment.
// show the title of the image when hovering the associated dot.
Here is the javascript. The other files can be seem at jsfiddle
$(document).ready(function() {
var carouselItems = [
{ src: "http://placehold.it/600x300/cccccc/000000", title: "Sample 01" },
{ src: "http://placehold.it/600x300/f45a45/000000", title: "Sample 02" },
{ src: "http://placehold.it/600x300/b78d65/000000", title: "Sample 03" },
{ src: "http://placehold.it/600x300/666aa0/000000", title: "Sample 04" },
{ src: "http://placehold.it/600x300/cccddd/000000", title: "Sample 05" }
];
Carousel = function() {
// keep track of the current position
var position = 0;
// build carousel based on items in the carouselItems array
$(carouselItems).each(function(index, value){
var li = $('<li/>');
li.addClass('carousel-item');
li.css('width', 100 / carouselItems.length + '%');
li.appendTo($('#carousel'));
var img = $('<img/>');
img.attr('src', value.src);
img.appendTo(li);
var liDot = $('<li/>');
liDot.addClass('carousel-dots-nav-item').html('o');
liDot.appendTo($('#carousel-dots-nav'));
});
// increase width of the carousel
$('#carousel').css('width', carouselItems.length * 100 + '%');
// add events to dots
for (i = 0; i < $('.carousel-dots-nav-item').length; i++) {
var dot = $('.carousel-dots-nav-item')[i];
// show the title of the image when hovering the associated dot
$(dot).hover(function(e){
$('#title').text(carouselItems[i].title);
}, function(e){
$('#title').text('');
});
// move to the appropriate slide when a dot is clicked
$(dot).click(function(e){
position = i;
$('#carousel').animate({
left: -position * 100 + '%'
}, 500);
});
}
// add click event to next button
$("#next").click(function(e){
e.preventDefault();
if (position == carouselItems.length - 1) return;
position++;
$('#carousel').animate({
left: -position * 100 + '%'
}, 500);
});
// add click event to previous button
$("#previous").click(function(e){
e.preventDefault();
if (position == 0) return;
position--;
$('#carousel').animate({
left: -position * 100 + '%'
}, 500);
});
};
var carousel = new Carousel();
});