Reputation: 6756
I just want to do simple slider based on margin-left css property, but it looks that the result is not rendered between partial margin-left increments. What is wrong with my code?
https://jsfiddle.net/1utkr6et/
html:
<div class="main-padding">
<div id="wrapper-slider">
<div class="item-slider item-slider1"></div>
<div class="item-slider item-slider2"></div>
<div class="item-slider item-slider3"></div>
</div>
</div>
css:
* {
border: 0;
margin: 0;
padding: 0;
outline: 0;
}
a {
text-decoration: none;
color: inherit;
}
body {
font-size: 62.5%;
}
ul, ol {
list-style-type: none;
}
.main-padding {
padding: 20px;
}
#wrapper-slider {
height: 200px;
position: relative;
overflow: hidden;
}
.item-slider {
width: 100%;
float: left;
height: 100%;
}
.item-slider1 {
background-color: red;
}
.item-slider2 {
background-color: blue;
}
.item-slider3 {
background-color: yellow;
}
js(jquery):
$(function () {
var item = ".item-slider";
var next = 1;
setInterval(function() {
$(item + next).animate({"marginLeft": "-100%"}, 1000);
next++;
}, 2000);
});
Upvotes: 2
Views: 96
Reputation: 5361
You need to specify a width for wrapper-slider eg width:300%;
100% for each slide. However the padding
for main-padding
makes it dificult for the slides as they are next to each other so you can see about 20px of the next slide. Unless there is a better way i suggest not using the padding as i have in the Demo.
You also need to calculate each slides width too.
Demo
https://jsfiddle.net/twgvxj1z/
Code
var tt = $(window).width();
$(".item-slider").css("width", tt+"px");
Upvotes: 1
Reputation: 6588
The main problem with your slider is that you are defining the elements of slider float
. I have made a few changes in your code to make this work properly.
CSS:
.item-slider {
position: absolute;
left: 100%;
width: 100%;
height: 100%;
}
JavaScript:
$(function () {
var item = ".item-slider";
var next = 1;
var current;
setInterval(function() {
if(next === 1){
prev = $(item + 3);
}else{
prev = $(item + (next - 1));
}
current = $(item + next);
current.css({"left": "100%"});
current.animate({"left": "0"}, 1000);
prev.animate({"left": "-100%"}, 1000);
if(next === 3){
next = 1;
}else{
next++;
}
}, 2000);
});
FIDDLE: https://jsfiddle.net/lmgonzalves/1utkr6et/5/
Upvotes: 1