I have a jQuery script that creates a carousel to rotate images left and right on user click. At first, I wasnt planning on putting more than one carousel on a single page, but now the need has arrived.
The problem is, I dont know how to refer to one carousel (the one clicked) when the user clicks a button.
Heres the script
$(function()
{
// Put last item before first item, in case user clicks left
$('.carousel li:first').before($('.carousel li:last'));
// Right click handler
$('.right-button img').click(function()
{
// Get width plus margins
var item_width = $('.carousel li').outerWidth() + (2 * parseInt($('.carousel li').css('margin-right')));
// Get left indent
var orig_left_indent = $('.carousel').css('left');
// Calculate new left indent
var left_indent = parseInt(orig_left_indent) - item_width;
$('.carousel:not(:animated)').animate({'left': left_indent}, 500, 'swing', function()
{
// Put first item after last item
$('.carousel li:last').after($('.carousel li:first'));
// Set left indent to default
$('.carousel').css({'left': orig_left_indent});
});
});
// Left click handler
$('.left-button img').click(function()
{
// Get width plus margins
var item_width = $('.carousel li').outerWidth() + (2 * parseInt($('.carousel li').css('margin-right')));
// Get left indent
var orig_left_indent = $('.carousel').css('left');
// Calculate new left indent
var left_indent = parseInt(orig_left_indent) + item_width;
$('.carousel:not(:animated)').animate({'left': left_indent}, 500, 'swing', function()
{
// Put last item before first item
$('.carousel li:first').before($('.carousel li:last'));
// Set left indent to default
$('.carousel').css({'left': orig_left_indent});
});
});
// Close button handler
$('.carousel-container .close-button img').click(function()
{
$('.carousel-container').fadeOut(1000);
});
});
As of now, when you click right or left on any carousel, all of them shift. I dont know how to get a reference to the carousel clicked.
heres the HTML
<div class="carousel-container clearfix">
<div class="header close-button">
<strong>Check These Out</strong>
<?php echo html::image('media/images/close.gif'); ?></div>
<div class="left-button"><?php echo html::image('media/images/left_arrow.png'); ?></div>
<div class="carousel-inner">
<ul class="carousel">
<?php foreach ($items as $item): ?>
<li> ... </li>
<?php endforeach; ?>
</ul>
</div>
<div class="right-button"><?php echo html::image('media/images/right_arrow.png'); ?></div>
</div>
How would I achieve this, I dont know how to reference the carousel that the user clicked, because the arrows are child elements of the carousel.
EDIT: Thanks for the answers. carousel = $(this).parent()
works, but how do I check if the carousel is :animated using the selector and the new carousel variable?
$(':animated', carousel) ?