Vahagn Sargsyan Vahagn Sargsyan - 3 months ago 9
jQuery Question

jQuery before doesn't work

I'm trying to make an infinite carousel. i have this in my html:

<div class="logo-mini-scroller floatInner toLeft">
<span class="_l toLeft">
<a href="javascript:void(0)"></a>
</span>
<div id="carousel_inner">
<ul class="_cont toLeft" id="carousel_ul">
<li class="mini-1">
<a href="#"></a>
</li>

<li class="mini-2">
<a href="#"></a>
</li>

<li class="mini-3">
<a href="#"></a>
</li>
</ul>
</div>
<span class="_r toRight">
<a href="javascript:void(0)"></a>
</span>
</div>


and i have this in my javascript

$(document).ready(function() {
$('#carousel_ul li:first').before($('#carousel_ul li:last'));

$('.logo-mini-scroller span._r.toRight').click(function(){
var item_width = $('#carousel_ul li').outerWidth() + 10;
var left_indent = parseInt($('#carousel_ul').css('left')) - item_width;

$('#carousel_ul').animate({'left' : left_indent},{queue:false, duration:500},function(){
$('#carousel_ul li:first').insertAfter($('#carousel_ul li:last'));
$('#carousel_ul').css({'left' : '-93px'});
});
});

$('.logo-mini-scroller span._l.toLeft').click(function(){
var item_width = $('#carousel_ul li').outerWidth() + 10;
var left_indent = parseInt($('#carousel_ul').css('left')) + item_width;

$('#carousel_ul').animate({'left' : left_indent},{queue:false, duration:500},function(){
$('#carousel_ul li:first').before($('#carousel_ul li:last'));
$('#carousel_ul').css({'left' : '-93px'});
});

});

$('#carousel_ul li').click(function(){
var self = this;

$('#carousel_ul li').each(function(){
if ($(this).hasClass('active')){
$(this).removeClass('active');
}

$(self).addClass('active');
})
});

});


the jQuery before and after functions doesn't work. All the animation works good, but does not prepend and append the elements. I also tried inserBefore and inserAfeter, but got the same result.

Answer

The issue is your animate function. You need to set complete option in your arguments.

Instead of

{'left' : left_indent},{queue:false, duration:500},function(){

Use:

{'left' : left_indent},{queue:false, duration:500, complete: function(){ 

Here is a working example: https://jsfiddle.net/ufcmos2y/

Comments