Loop Function on Mouseover in Vanilla Javascript

Viewed 363

I am trying to create a carousel of images and wanted to horizontal scroll when the user hovers over the left and right side of the div. I have two "invisible" divs for the left and right controls and gave them eventListeners:

right.addEventListener("mouseover", goRight)

function goRight() {
    document.getElementById('images').scrollLeft += 20;
}

left.addEventListener("mouseover", goLeft)

function goLeft() {

    document.getElementById('images').scrollLeft -= 20;
}

When I hover over them, it will scroll once, but I would like it to continuously scroll until I mouseout. How I can I make goRight()/goLeft() loop while I am hovering on the controls?

2 Answers

One solution is to use the setInterval() method which should be cancelled on mouseout. You can store the interval id and use clearInterval() on mouseout:

const delay = 100;
let intervalId;

function goLeft() {
  intervalId = setInterval(
    () => (document.getElementById('images').scrollLeft -= 20),
    delay,
  );
}

function goRight() {
  intervalId = setInterval(
    () => (document.getElementById('images').scrollLeft += 20),
    delay,
  );
}

function stopScrolling() {
  clearInterval(intervalId);
}

left.addEventListener('mouseover', goLeft);
left.addEventListener('mouseout', stopScrolling);
right.addEventListener('mouseover', goRight);
right.addEventListener('mouseout', stopScrolling);

You can create a Boolean that will be 'true' when the user has his mouse over the element.

// for the right side:
let mouseOverRight = false;


right.addEventListener("mouseenter", function(){
    mouseOverRight = true;
});
right.addEventListener("mouseleave", function(){
    mouseOverRight = false;
});

Then using an interval, change the delay to whatever speed you want

window.setInterval(function(){
  if (mouseOverRight)
  /// Scroll logic here
}, 300);

Then of course you would have to do the same for the left side.

Related