I am trying to create simple vanilla Javascript slider but i am having some issues, hopefully someone can help me.
html code :
<div class="box" id="boxid">
<div class="inside_box" id="inside_box_id">
<ul class="main_ul" id="main_ul_id">
<li class="one" id="oneid"><a href = "#"></a></li>
<li class="one" id="twoid"><a href = "#"></a></li>
<li class="one" id="threeid"><a href = "#"></a></li>
<li class="one" id="fourid"><a href = "#"></a></li>
<li class="one" id="fiveid"><a href = "#"></a></li>
</ul>
</div> <!-- end of inside_box -->
</div><!-- end of box -->
<button id="previd" class="btn">Prev</button>
<button id="nextid" class="btn">Next</button>
css code:
body {
background:grey;
font-family: sans-serif;
}
.box {
width:800px;
height:300px;
border:1px solid black;
margin: 0 auto;
}
.inside_box {
width:800px;
height:300px;
padding:0px;
margin:0px;
overflow: hidden;
}
.main_ul {
width:4000px;
padding:0px;
margin:0px;
}
.main_ul li {
list-style: none;
float:left;
}
.one {
width:800px;
height:300px;
}
#oneid {background:blue;}
#twoid {background:orange;}
#threeid {background:brown;}
#fourid {background:green;}
#fiveid {background:purple;}
.btn {
padding:10px;
width:100px;
margin-left:50%;
cursor: pointer;
margin-top:10px;
}
JS code
var prevBtn = document.getElementById("previd");
var nextBtn = document.getElementById("nextid");
nextBtn.addEventListener("click", function(){
var slideLeft = document.getElementById("main_ul_id");
slideLeft.style.marginLeft = "-800px";
}, false);
At the moment when i click the Next button it takes me to the second slide but when i click it again it doesnt do anything. How can i make it so when i click it to margin-left 800px each time when it is clicked?
Thanks.
You need to get current value and subtract -800px
from it .
When you click Next button 1st time, it will set margin-left
as -800px
and you see the result. But for next press, it will again set margin-left
as -800px
.
Something like below:
nextBtn.addEventListener("click", function() {
var slideLeft = document.getElementById("main_ul_id");
var style = slideLeft.style;
var totalImages = 5;
var margin = 800;
style.marginLeft = (parseInt(style.marginLeft || "0") - margin)%(totalImages*margin) + "px";
}, false);
Taking remainder with (totalImages*margin)
will bring the first slide after hitting next from the last slide. Not the optimal logic but just to give you an idea.
Here's the working JSFiddle: https://jsfiddle.net/dsa3du93/7/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.