简体   繁体   中英

Images to stop toggling when mouseover but resume on mouseout

I have images that toggle between each other and when you hover over them they stop, but when you move away the mouse it doesn't want to resume the toggle. What am I doing wrong?

<script>
   var t;

  addEventListener("load", () => {
    var index = 0;
    const slides = document.querySelectorAll(".slides");
    const classHide = "slides-hidden",
      count = slides.length;
    nextSlide();
    function nextSlide() {
      slides[index++ % count].classList.add(classHide);
      slides[index % count].classList.remove(classHide);
      t = setTimeout(nextSlide, 500);
    }
  });

   $(".portfolio-image").mouseover(function () {
    if (t) {
      t = clearTimeout(t);
  }
  });

  $(".portfolio-image").mouseout(function () {
    if (t) {
      t = setTimeout(nextSlide, 500);
  }
  });

maybe this help you:

$(".portfolio-image").mouseover(function () {
    if (t) {
      clearTimeout(t);
  }
  });

The problem is "setTimeout" get called once, you want use "setInterval" and "clearInterval" instead.

Ok, I solved it with some help from you guys. setInterval is better for this task and I had to put it in the same scope as the variable t because it wasn't being read.

  var t;

  addEventListener("load", () => {

    var index = 0;
    const slides = document.querySelectorAll(".slides");
    const classHide = "slides-hidden",
      count = slides.length;
    nextSlide();
    t = setInterval(nextSlide, 500);
    function nextSlide() {
      slides[index++ % count].classList.add(classHide);
      slides[index % count].classList.remove(classHide);
    }

   $(".portfolio-image").mouseover(function () {
      clearInterval(t);
  });

  $(".portfolio-image").mouseout(function () {
    t = setInterval(nextSlide, 100);
  });

  });

Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM