Jquery Animation
Image gallery
by LyndseyB
HTML
<div id="wrapper">
<div id="img-container">
<div class="active"> Div1 </div>
<div> Div2 </div>
<div> Div3 </div>
<div> Div4 </div>
<div class="last"> Div5 </div>
</div>
</div>
CSS
#wrapper { width: 90%; margin: 0 auto; }
#img-container { position:relative; background: black; border:1px black solid; height:200px; }
#img-container div { background:lightblue; text-align:center; color:white; }
.absolute { position: absolute; }
JavaScript
//min width for container
//min width for img
$(function() {
//container element
Container = $('#img-container');
//div elements
Div = $('#img-container').find('div');
//position elements absolutely
Div.addClass('absolute');
//number of divs
DivCount = Div.length;
//max container width
MaxWidth = Container.width();
//parent element width
ParentEl = Container.parent().width();
//percentage width of container relative to parent
MaxWidthP = MaxWidth/ParentEl*100;
//round max width to 100
MaxWidthR = MaxWidthP.toFixed(0);
//set width of each div relative to container
DivWidth = MaxWidthR/DivCount;
DivWidth = DivWidth.toFixed(2);
//set percentage width of each, but take of 2% each to later apply 1% margin
Div.css("width", DivWidth+'%');
//this is the width of each separate element
elWidth = MaxWidth/DivCount;
//animate function
Div.not('.active').each(function(index) {
counter = index + 2;
el = $('#img-container div:nth-child(' + counter + ')');
el.animate({
"left": (elWidth)*(counter-1) + 'px'
}, 1000, function() { //Animation Complete
//position divs as floats so they become responsive
Div.removeClass('absolute').css("float", "left");
Div.not('.active').css({
// margin: "0 1%"
});
el.animate({"top": (elWidth)*(counter-1) + 'px'}, 1000);
});
});
});