I am trying to create a really simple slider using 2 buttons the will increase the margin when hovered over. I would like the buttons to increase or decrease the margins continuously.
At the minute I can only get them to move in set chunks. Could anyone point me in the right direction?
var left = document.querySelector(".left");
var right = document.querySelector(".right");
var slide = document.querySelector(".slider");
left.onmouseover = function() {
var currentLeftMargin = getComputedStyle(slide).marginLeft;
console.log(currentLeftMargin);
// Element's style = number portion of current style, then do math, then add back on the unit
slide.style.marginLeft = (parseInt(currentLeftMargin, 10) - 900) + "px";
}
right.onmouseover = function() {
var currentLeftMargin = getComputedStyle(slide).marginLeft;
console.log(currentLeftMargin);
// Element's style = number portion of current style, then do math, then add back on the unit
slide.style.marginLeft = (parseInt(currentLeftMargin, 10) + 900) + "px";
}
``` .slide-container {
height: 300px;
width: 100%;
background-color: blue;
position: relative;
overflow: hidden;
}
.left {
position: absolute;
height: 20px;
width: 20px;
background-color: red;
top: 50%;
left: 0;
}
.right {
position: absolute;
height: 20px;
width: 20px;
background-color: red;
top: 50%;
right: 0;
}
.slider {
height: 300px;
width: 100%;
display: flex;
left: 0;
transition: all ease 1s;
}
.slider:hover {}
.item {
display: block;
height: 300px;
width: 300px;
min-width: 300px;
background-color: green;
margin-left: 10px;
}
<div class="slide-container">
<div class="left"></div>
<div class="right"></div>
<div class="slider">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
</div>
<div class="fade"></div>
</div>
3
Answers
You would need an interval which sets the margin at consequent steps, by creating an Interval with
setInterval(function(), milliseconds);
To be able to terminate the interval and preventing of creating endless amounts of intervals, we need to store the ID of the Interval in a variable.
iId = setInterval(function(), milliseconds);
We then would terminate the interval if the mouse leaves the element by
clearInterval(IntervalID);
As you used a css-transition to smoothen the animation, i had to fiddle abit with the steps of margin increase and decrease and the interval, so there aren’t any "jumps".
You can use
setInterval
to repeat the movement you’re currently doing inonmouseover
for it to keep advancing.Remember to
clearInterval
inonmouseout
Here’s an example
To do what you require you can use an interval which you set to update each frame of movement of the
.slide
element.You can also use
Math.min()
andMath.max()
to limit the movement of the slider to its contents.