Reputation: 16513
How can I hide prev/next controller if "li.item:first" or "li.item:last" has "active" class
<ul class="carousel">
<li class="item active"><img src="ab.jpg" /></li>
<li class="item"><img src="cd.jpg" /></li>
<li class="item"><img src="ef.jpg" /></li>
<li class="item"><img src="gh.jpg" /></li>
</ul>
<!-- Controls -->
<a class="left carousel-control" href="#carousel" data-slide="prev">
<span class="icon-prev"></span>
</a>
<a class="right carousel-control" href="#carousel" data-slide="next">
<span class="icon-next"></span>
</a>
Upvotes: 2
Views: 131
Reputation: 28196
Alternatively you can start by identifying the active li
first and then check whether it is the first or last in the current ul
:
$('.left.carousel-control').toggle(!$('li.active').is(':first-child'));
$('.right.carousel-control').toggle(!$('li.active').is(':last-child'));
Upvotes: 0
Reputation: 550
Great answers here is an alternative solution, I slightly change the above code and remove duplication.
css
.carousel .item
{
display: none;
}
.carousel .item.active
{
display: block;
}
jquery
$(function()
{
$('.carousel-control').click(function(event)
{
event.preventDefault();
var $this = $(this)
var direction = $this.data('slide');
var $items = $('.carousel .item');
var $activeItem = $items.filter('.active');
var $nextItem = $activeItem[direction]();
var hasItem = $nextItem.length !== 0;
var shouldHideControl = $nextItem.is(':first-child') || $nextItem.is(':last-child');
var $controls = $('.carousel-control');
$controls.show()
if(hasItem)
{
$items.removeClass('active');
$nextItem.addClass('active');
}
if(shouldHideControl)
{
$this.hide();
}
});
});
Upvotes: 1
Reputation: 3222
if $('li.item:first').hasClass('active') { $('a.left.carousel-control').toggle(); }
if $('li.item:last').hasClass('active') { $('a.right.carousel-control').toggle(); }
Not a complete solution, but should get you started. Just work with those in your click handlers.
Upvotes: 1
Reputation: 78525
You'll need to do this each time your active class changes, i.e. Each time the carousel changes slide.
// Show both by default
$(".left, .right").show();
// If the first is selected, hide the left
if($("li.item:first").hasClass("active")) $(".left").hide();
// If the last is selected, hide the right
if($("li.item:last").hasClass("active")) $(".right").hide();
Upvotes: 0
Reputation: 12974
You could do it this way:
$(".right").click(function() {
if($(".active").is(":last-child"))
{
$(this).hide();
$(".left").show();
}
}
And then the opposite (swap lefts and rights) for the "previous" control.
Upvotes: 4
Reputation: 11302
Something like this should do it:
if($('li.item:first').hasClass('active')) {
$('a.carousel-control.left').hide();
}else {
$('a.carousel-control.left').show();
}
if($('li.item:last').hasClass('active')) {
$('a.carousel-control.right').hide();
}else {
$('a.carousel-control.right').show();
}
Upvotes: 1