Bezzzo Bezzzo - 4 months ago 8
Javascript Question

Jquery animate stops working on a specific element after a previous animation

I have been playing around with a small slider with HTML and Jquery. It's supposed to work by sliding off the screen, either left or right depending which way the user navigates, then returning via animation to it's original starting point.

Though as soon as i click the 'left' animation the 'right' animation wont animate anymore.

Clicking the 'right' animation has no effect on the 'left' animation, it still appears to work fine though visa versa it's a different story and i'm not sure why.

I have made a JSfiddle of my problem.

I have read an article on Reset CSS Animation but it doesn't seem to help me at all.

Maybe someone can help me spot what i'm missing

HTML:

<!-- Product Slider -->
<div id="index_slider_container" class="">

<a id='slide_left' href'#'>left</a>

<!-- Slider shaft -->
<div id="slider_shaft" class="">
<div id="slider_product_container" class="">

<!-- Product Image -->
<div id="slider_product_image" class="">

</div>

<!-- Product name -->
<div id="slider_product_name" class="">

</div>
</div>
</div>
<a id='slide_right' href'#'>right</a>
</div>


JQuery

// Slider left
$("#slide_left").click( function(){

$("#slider_shaft").css('left', '100%');

// Set time out and return div VIA animation
setTimeout( function(){
$("#slider_shaft").animate({left: '0%'}, 500);
}, 200);

});

// Slider right
$("#slide_right").click( function(){

$("#slider_shaft").css('right', '100%');

// Set time out and return div VIA animation
setTimeout( function(){
$("#slider_shaft").animate({right: '0%'}, 500);
}, 200);

});


CSS

#index_slider_container {
position: relative;
height: 120px;
width: 97%;
margin: 15px;
overflow: hidden;
border: 1px solid;
text-align: center;
}

#slider_shaft {
position: relative;
height: 120px;
width: 100%;
border: 1px solid;
text-align: center;
}

#slider_product_container {
display: inline-block;
height: 100%;
width: 120px;
border: 1px solid;
margin-left: 5px;
}

#slider_product_image {
height: 80%;
width: 100%;
border: 1px solid;
}

#slider_product_name {
height: 20%;
width: 100%;
border: 1px solid;
}

#slide_left {
border: 1px solid;
padding: 5px;
cursor: pointer;
position: absolute;
z-index: 5;
left: 0;
top: 0;
}

#slide_right {
border: 1px solid;
padding: 5px;
cursor: pointer;
position: absolute;
z-index: 5;
right: 0;
top: 0;
}

Answer

Try setting the opposite direction to auto:

$("#slider_shaft").css('left', '100%');    
$("#slider_shaft").css('right', 'auto');

and

$("#slider_shaft").css('right', '100%');    
$("#slider_shaft").css('left', 'auto');

The problem is that the left attribute stays set, even after the Right button is clicked. You need to return it to default.

Comments