Skip to content
Advertisement

Change JS scrolling event to time interval

I have an image gallery I’m using for a webpage. Currently, the gallery images change when the user scrolls, but I’d like to change it so that the images change on a time interval, and are on a loop instead of an up scroll to go back and a down scroll to go forward. I’m pretty new to Javascript, so I’m now sure how to change the below script from scrolling to timed.

<script>
$(document).ready(function() {
  var curPage = 1;
  var numOfPages = $(".skw-page").length;
  var animTime = 1000;
  var scrolling = false;
  var pgPrefix = ".skw-page-";

  function pagination() {
    scrolling = true;

  $(pgPrefix + curPage).removeClass("inactive").addClass("active");
  $(pgPrefix + (curPage - 1)).addClass("inactive");
  $(pgPrefix + (curPage + 1)).removeClass("active");

  setTimeout(function() {
    scrolling = false;
  }, animTime);
};

  function navigateUp() {
    if (curPage === 1) return;
    curPage--;
    pagination();
  };

  function navigateDown() {
    if (curPage === numOfPages) return;
    curPage++;
    pagination();
  };

  $(document).on("mousewheel DOMMouseScroll", function(e) {
    if (scrolling) return;
    if (e.originalEvent.wheelDelta > 0 || e.originalEvent.detail < 0) {
      navigateUp();
    } else { 
      navigateDown();
    }
  });

  $(document).on("keydown", function(e) {
    if (scrolling) return;
    if (e.which === 38) {
      navigateUp();
    } else if (e.which === 40) {
      navigateDown();
    }
  });
});
</script>

Advertisement

Answer

Just call setInterval, change what happens when navigateDown is called once all pages have been cycled through, and remove the scroll/keydown listeners.

$(document).ready(function() {
  var curPage = 1;
  var numOfPages = $(".skw-page").length;
  var animTime = 1000;
  var scrolling = false;
  var pgPrefix = ".skw-page-";

  function pagination() {
    scrolling = true;

    $(pgPrefix + curPage)
      .removeClass("inactive")
      .addClass("active");
    $(pgPrefix + (curPage - 1)).addClass("inactive");
    $(pgPrefix + (curPage + 1)).removeClass("active");
    if (curPage === 1) $(pgPrefix + numOfPages).addClass("inactive");

    setTimeout(function() {
      scrolling = false;
    }, animTime);
  }

  function navigateDown() {
    if (curPage === numOfPages) curPage = 0;
    curPage++;
    console.log(curPage);
    pagination();
  }

  setInterval(navigateDown, 5000); // 5000 ms == 5 s
});
.active {
  color: purple;
}

.inactive {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>
  <p class="skw-page skw-page-1 active">Page 1</p>
  <p class="skw-page skw-page-2 inactive">Page 2</p>
  <p class="skw-page skw-page-3 inactive">Page 3</p>
  <p class="skw-page skw-page-4 inactive">Page 4</p>
</div>
Advertisement