Reputation: 1183
I have a project where I have a horizontal bar that has an overflow. At the beginning and end there are buttons that move the overflow position. At this point the user has to click on the buttons in order to move the overflow.
I wan't to create buttons that when hovered over them keep continuously keep on moving the overflow until the end is reached or when the user removed the mouse from the buttons. The code
I have tried to change the 'oclick' to a 'onmouseover' and make the function async. Then add a second 'onmouseout' function. But I keep on getting and endless loop and the web application breaks.
let isHovered = false;
async function scollTopBar(direction) {
var parent = document.getElementById("parent");
isHovered = true;
let amount = 1;
while(isHovered){
if (direction === "left") amount *= -1;
parent.scrollLeft += amount;
setTimeout(() => {}, 100);
}
}
function mouseRemoved() {
isHovered = false;
}
I did not include the above code so to not break the browser.
var parent = document.getElementById("parent")
function scollTopBar(direction) {
var parent = document.getElementById("parent");
let amount = 20;
if (direction === "left") amount *= -1;
parent.scrollLeft += amount;
}
.cotainer {
width: 30rem;
height: 3rem;
display: flex;
background-color: red;
}
p{
margin: 0;
padding: 0;
white-space: nowrap;
}
button {
height: 100%;
}
.parent {
height: 100%;
display: flex;
align-items: center;
overflow: auto;
}
.child {
padding: 0 1rem;
border-right: 1px solid blue;
background-color: green;
display: inline-flex;
}
<div class="cotainer">
<button onclick="scollTopBar('left')">b</button>
<div class="parent" id="parent">
<div class="child">
<p>Hello</p>
<p>Hello</p>
</div>
<div class="child">
<p>Hello World</p>
<p>Hello</p>
</div>
<div class="child">
<p>Hello WorldHelloWorld</p>
<p>Hello</p>
</div>
<div class="child">
<p>World</p>
<p>Hello</p>
</div>
<div class="child">
<p>Hello WorldHello World</p>
<p>Hello</p>
</div>
<div class="child">
<p>Hello</p>
</div>
<div class="child">
<p>HelloWorld</p>
<p>Hello</p>
</div>
<div class="child">
<p>HelloWorld</p>
<p>Hello</p>
</div>
</div>
<button onclick="scollTopBar('right')">n</button>
</div>
Upvotes: 0
Views: 126
Reputation: 158
in vanilla JS you should have something like this where left and right are the buttons --->
let left = document.getElementById("left");
let right = document.getElementById("right");
left.onmouseover = () => {
scrollTopBar(-20);
};
right.onmouseover = () => {
scrollTopBar(20);
};
function scrollTopBar(direction) {
var parent = document.getElementById("parent");
let int = setInterval(() => {
parent.scrollLeft += direction;
}, 100);
left.onmouseout = () => {
clearInterval(int);
};
right.onmouseout = () => {
clearInterval(int);
};
}
Upvotes: 1