Dynamic full-width content slider
by lasha
HTML
<div class="main-container">
<div class="container">
<div style="background: url('http://placekitten.com/400/150') no-repeat center top;">floateded div0</div>
<div style="background: url('http://placekitten.com/620/150') no-repeat center top;">floateded div1</div>
<div style="background: url('http://placekitten.com/440/150') no-repeat center top;">floateded div2</div>
</div>
</div>
<span class="prev">previous</span>
<span class="next">next</span>
CSS
body {
margin: 0;
}
.main-container {
position: relative;
overflow: hidden;
/* width: 400px; */ /* optional, remove for full-width animation */
margin: 0 auto;
}
.container {
position: relative;
}
.container div {
float: left;
width: 100%;
height: 150px;
border: 1px solid #000;
/* box-sizing: border-box; */
/* background: url("http://placekitten.com/440/150") no-repeat center top; */
}
JavaScript
var myObject = {
theWidth: 0,
getTheElements: function(){
return $(".container div");
},
$theElements: "", // blank default, overwritten by getParentEl
getWidth: function(){
//console.log(this.theWidth);
},
getParentEl: function(){
console.log(this.$theElements.parent().width());
return this.$theElements.parent();
},
$parentEl: "", // default is blank, overwritten by getParentEl
elsCount: 1,
activeEl: 0,
setWidth: function(newWidth){
console.log("newWidth is: " + newWidth);
this.theWidth = newWidth;
this.$theElements.outerWidth(this.theWidth);
this.$parentEl.width( this.theWidth * this.elsCount );
},
init: function(){
this.$theElements = this.getTheElements();
this.elsCount = this.$theElements.length;
this.$parentEl = this.getParentEl();
}
}
myObject.init();
// myObject.setWidth(150);
// myObject.getWidth();
$(function(){
var $window = $(window);
$window.resize(function(event){
var newWidth = $('.main-container').width(); // used to be $(window).width();
myObject.setWidth(newWidth);
//myObject.getWidth();
myObject.$parentEl.css({
left: -myObject.theWidth * myObject.activeEl
});
}).resize();
$(".next").on("click", function(){
if(myObject.$parentEl.is(':animated')){
console.log("BAHAAHAH!");
return;
}{
myObject.activeEl += 1;
if (myObject.activeEl >= myObject.$theElements.length){
myObject.$parentEl.animate({
left: 0
},1000);
myObject.activeEl = 0;
} else {
myObject.$parentEl.animate({
left: -myObject.theWidth * myObject.activeEl
},1000);
}
}
console.log("active el: ", myObject.activeEl);
});
...