I've tried to make a dragabe slider at first glance it seems to work fine. But upon sliding it more than once you'll notice it bugs out.
It looks like it teleports to the mouse position on the first mousemovement. I've tried several things but can't wrap my head around it.
My html:
<div class="container">
<div class="slider-wrapper" v-on:mousemove="slide()">
<div class="slider">
<div class="slide"></div>
<div class="slide"></div>
<div class="slide"></div>
<div class="slide"></div>
</div>
</div>
</div>
My javascript:
export default {
data() {
return {
mouseDown: 0,
start: undefined,
position: undefined,
}
},
methods: {
slide() {
const vm = this
document.body.onmousedown = function () {
vm.start = window.event.clientX
vm.mouseDown = 1
}
document.body.onmouseup = function () {
vm.mouseDown = 0
}
if (this.mouseDown == 1) {
vm.position = window.event.clientX - vm.start
document.querySelector('.slider').style.left = vm.position + 'px'
}
},
},
}
I've recreated a demo of my problem.
Turns out i needed to remember the old reposition before repositioning the slider. To fix this i changed the code as following:
data() {
return {
mouseDown: 0,
start: undefined,
position: undefined,
old_pos: 0 // initialize old_pos
}
},
slide() {
const vm = this
document.body.onmousedown = function() {
vm.start = window.event.clientX
vm.mouseDown = 1
}
document.body.onmouseup = function() {
vm.old_pos = vm.position + vm.old_pos // Sets old_pos when a new position has been set.
vm.mouseDown = 0
}
if(this.mouseDown == 1) {
vm.position = window.event.clientX - vm.start
document.querySelector(".slider").style.left = vm.position + vm.old_pos + "px"; // Adds the old position as starting point of movement.
}
}