Search code examples
javascripthtmlonmouseoveronmouseout

onmouseover and onmouseout setInterval


I have been stuck with this problem. I am using slider for my app. For sliding the app I am using splide-js. My image slider works fine.

I have connected my slider with my li elements. I want to make custom onmouseover and onmouseout events. When the user triggers mouseover on li it will pause and when mouseout it will resume the slide.

I was checking this Stack Overflow post and tried to do logic like the person by using setinterval but could not able to do that.

const autoPlay = false;
const pauseOnHover = document.getElementById('pause');

function nextSlide() { //I don't what kind logic I should use to pause the slide

}

let  timer = setInterval(function() {
  nextSlide();
}, 400);


pauseOnHover.onmouseover = () => {
  if( autoPlay) {
    timer
  }
}
pauseOnHover.onmouseout = () => {
  if (autoPlay) {
    clearInterval(timer)
  }
}
<div class='checklist' id="pause">
  <ol>
    <li id="link-1">Assign jobs in an instant.</li>
    <li id="link-2">Always see what's happening.</li>
    <li id="link-3">Easy to set-up & use.</li>
    <li id="link-4">Be more sustainable</li>
  </ol>
</div>


Solution

  • Please intilaize and reintiliaze the interval on mousehover, onmouseout if interval exists cancel it.

    Please try below code.

    const autoPlay = false;
    const pauseOnHover = document.getElementById('pause');
    
    function nextSlide() {
      //For example I have put console.log, you mat put any code block here.
      console.log("hello");
    }
    
    let timer;
    
    
    pauseOnHover.onmouseover = () => {
    
      autoplay = true;
      if (!autoPlay) {
        autoplay = true;
        timer = setInterval(function() {
          nextSlide();
        }, 400);
      }
    }
    pauseOnHover.onmouseout = () => {
    
      autoplay = false;
      timer && clearInterval(timer)
    
    }
    <div class='checklist' id="pause">
      <ol>
        <li id="link-1">Assign jobs in an instant.</li>
        <li id="link-2">Always see what's happening.</li>
        <li id="link-3">Easy to set-up & use.</li>
        <li id="link-4">Be more sustainable</li>
      </ol>
    </div>