I'm trying to make a slider bar gallery scroll with the Mouse Teaching in JavaScript but I have an issue when I'm trying to scroll on touching the element the elements is shaking, I would like to know what I'm doing wrong
My Screen Recording: Demo of the Problem
My Code:
let mouseUpStatus = false;
let mouseMoveStatus = false;
let mouseEnterStatus = false;
let pressed = false;
let slidebar = document.querySelector(".box");
let inSlidebar = document.querySelector(".v");
let c = document.querySelector(".c");
let widthC = c.offsetWidth;
let newX = 0;
slidebar.addEventListener('mousemove', (e) =>{
if(pressed){
newX = widthC e.offsetX;
inSlidebar.style.transform = "translateX(" newX "px)";
}
});
slidebar.addEventListener('mouseup', (e) =>{
pressed = false;
});
slidebar.addEventListener('mousedown', (e) =>{
pressed = true;
});
div.box{
width: 480px;
overflow: hidden;
}
div.v{
display: flex;
transform: translateX(0px);
}
::-webkit-scrollbar {
width: 0; /* Remove scrollbar space */
background: transparent; /* Optional: just make scrollbar invisible */
}
div.c {
width: 24%;
height: 60px;
background-color: skyblue;
flex-shrink: 0;
margin-right: 1%;
}
<div >
<div >
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
<div >7</div>
</div>
</div>
Thank You!
CodePudding user response:
let slidebar = document.querySelector(".box");
let inSlidebar = document.querySelector(".v");
let c = document.querySelector(".c");
let widthC = c.offsetWidth;
let slidevalue = 0;
function slideNext() {
slidevalue = widthC;
document.getElementById("vt").style.transform = "translateX(-" slidevalue "px)";
}
function slidePrev() {
slidevalue -= widthC;
document.getElementById("vt").style.transform = "translateX(-" slidevalue "px)";
}
div.box{
width: 480px;
overflow: hidden;
}
div.v{
display: flex;
transform: translateX(0px);
}
::-webkit-scrollbar {
width: 0; /* Remove scrollbar space */
background: transparent; /* Optional: just make scrollbar invisible */
}
div.c {
width: 24%;
height: 60px;
background-color: skyblue;
flex-shrink: 0;
margin-right: 1%;
}
<table>
<tr>
<td><button id="prev" onclick="slidePrev()">left</button></td>
<td>
<div >
<div id="vt">
<div >1</div>
<div >2</div>
<div >3</div>
<div >4</div>
<div >5</div>
<div >6</div>
<div >7</div>
</div>
</td>
<td><button id="next" onclick="slideNext()">right</button></td>
</div>
</tr>
</table>
CodePudding user response:
I found the problem - it is because the mouse moves very fast. I am using CSS property left
and adding that e.target.offsetLeft
instead of e.offsetX
, and inSlidebar.style.left
instead of inSlidebar.style.transform
The new CSS looks like this:
div.v {
display: flex;
position: relative;
top: 0;
left: -10px;
transform: translateX(0px);
transition: left 2s;
}