I am having issues with jQuery animations on a really simple slider. The first time you click on them the animation seems buggy. The animations make the divs break the container. I add overflow: hidden to the containing div, but it just makes the content ‘flash’ instead of overflow underneath.
After the first click of each element, the animations are fine. Any idea how to avoid this behaviour?
Here is the example: http://jsbin.com/izuviv/edit#preview
HTML
<div id="slider">
<div class="slide expanded">
<img />
<a href="">
<h3>Lorem</h3>
<p>Ipsum</p>
</a>
</div>
<div class="slide">
<img />
<a href="">
<h3>Lorem</h3>
<p>Ipsum</p>
</a>
</div>
<div class="slide">
<img />
<a href="">
<h3>Lorem</h3>
<p>Ipsum</p>
</a>
</div>
<div class="slide last">
<img />
<a href="">
<h3>Lorem</h3>
<p>Ipsum</p>
</a>
</div>
</div>
CSS
#slider {width: 632px; height: 231px; margin: 100px; font-family: arial, helvetica, sans-serif;}
#slider .slide {width: 71px; height: 231px; background: black; margin: 0 4px 0 0; float: left; display: inline; position: relative;}
#slider .slide a {display: block; width: 71px; height: 72px; background: transparent url(../img/white.png) 0 0 repeat; text-decoration: none; color: #000; position: absolute; bottom: 0;}
#slider .slide h3 {display: none;}
#slider .slide p {display: none;}
#slider .last {margin: 0;}
#slider .expanded {width: 407px;}
#slider .expanded a {width: 407px; background: transparent url(../img/white.png) 0 0 repeat;}
#slider .expanded h3 {margin: 10px 10px 0px 10px; font-size: 14px; font-weight: bold; display: block;}
#slider .expanded p {margin: 5px 10px; font-size: 12px; display: inline;}
JS
function slider() {
var slide = $('#slider div');
slide.click(function(){
var expanded = $('#slider .expanded');
if (!$(this).hasClass('expanded') ) {
// 1: Shrink expanded div
expanded.animate({
width: '71px'
}, 200, function() {
console.log('contract');
// 2: Remove expanded class
$(this).removeClass('expanded');
});
// 3: Add expanded class to clicked
$(this).addClass('expanded');
// 4: Expand clicked div
$(this).animate({
width: '407px'
}, 200, function() {
console.log('expand');
});
}
});
}
In the Function Slider, i changed the code into:
Now, it works fine..
I think what cause the problem is: $(this);.. Always save this into a variable to prevent errors and duplicates.