Can you please provide guidance on implementing automatic horizontal scrolling with pauses between each div?

setInterval(function scroll() {
  $(".box_auto").each(function(i, e) {
    $("html, body").animate({
      scrollTop: $(e).offset().top
    }, 500).delay(500);
  });
  setTimeout(function() {
    $('html, body').animate({
      scrollTop: 0
    }, 5000);
  }, 4000);
  return scroll;
}(), 9000);
.auto_scroll_top {
  overflow-x: scroll;
  overflow-y: hidden;
  white-space: nowrap;
  margin-top: 1.2rem;
}

.auto_scroll_top .box_auto {
  display: inline-block;
  min-width: 400px;
  height: 200px;
  background-color: orange;
  border-radius: 10px;
  margin: 0 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="auto_scroll_top">
  <div class="box_auto"></div>
  <div class="box_auto"></div>
  <div class="box_auto"></div>
  <div class="box_auto"></div>
</div>

I'm attempting to replicate a website and one of the tasks is the following. I have several divs (boxes) positioned horizontally that can be scrolled. I want them to automatically scroll from one div to the next, and then repeat the process at the end. So it should be something like div1 pause.. div2 pause.. etc.

Any suggestions on how to achieve this?

Answer №1

Here's a detailed example with comments explaining each step. I have added numbers to the div for clarity. You can also find a helpful solution on Stack Overflow, which I modified using the setInterval() method to iterate through elements (Source).

The code is well-commented for easy understanding.


// Start index
let auto_index = 0;

// Total count of divs
let total = document.getElementsByClassName('box_auto').length;

// Set interval
let timerId = setInterval( function() {

  // Increment index
  auto_index += 1; 
  
  // Reset if index exceeds total 
  if (auto_index > total - 1 ) {
    auto_index = 0;
  }
  
  scrollTo(auto_index);
  
}, 2000); // 2000 milliseconds


// Adapted from:
// https://stackoverflow.com/a/45388452/5604852
// Using .scrollIntoView with smooth and center options
function scrollTo(item) {
    document.getElementsByClassName('box_auto')[item].scrollIntoView({ behavior: 'smooth', block: 'center' });    
};
.auto_scroll_top{
    overflow-x: scroll;
    overflow-y: hidden;
    white-space: nowrap; 
    margin-top: 1.2rem;
}
.box_auto{
    display:inline-block;
    min-width:300px;
    height:200px;
    background-color: orange;
    border-radius: 10px;
    margin:0 5px;
}

.box_auto {
font-size: 150px;
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="auto_scroll_top">
  <div class="box_auto">1</div>
  <div class="box_auto">2</div>
  <div class="box_auto">3</div>
  <div class="box_auto">4</div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using the Chrome WebDriver for Selenium to interact with a text input element with dynamically changing IDs

I seem to be encountering difficulties with accessing an input element on a specific webpage. If the link has timed out, you can click on this following link: and then select the "RL_reactors" hyperlink to navigate to the page in question. On this page, ...

Creating phony passwords effortlessly in JavaScript utilizing the informal library

I am trying to create a password that meets the following criteria: Minimum length: 7 Maximum length: 15 At least one uppercase letter At least one lowercase letter Special characters: ~ ! @ # $ % ^ * ( ) _ + ? I have been using the casual library for g ...

Error encountered when attempting to send a jQuery Post to API due to Access-Control-Allow-Origin issue

I've been researching the 'Access-Control-Allow-Origin' error extensively, but I am still struggling to understand what needs to be fixed. Here's the code snippet in question: $.ajax({ url: 'http://54.149.190.45:8000/image/upl ...

What is the best way to execute 2 statements concurrently in Angular 7?

My goal is to add a key rating inside the listing object. However, I am facing an issue where the rating key is not displaying on the console. I suspect that it might be due to the asynchronous nature of the call. Can someone help me identify what mistak ...

The second scenario is triggered once the conditions are satisfied using a JavaScript switch case

(Here is a question dedicated to sharing knowledge.) I devised this switch statement to determine which recovery plan to suggest. const numPomodoros = 3; switch (0) { case numPomodoros % 3: console.log('I recommend coffee, V8, and 5 mi ...

File reading and processing must be completed before attempting to write to a new file. This is a promise-related stipulation

Feeling completely lost and stuck in a rut. Promises seemed straightforward until I actually tried to implement them. Sharing my basic code here without any promise attempts for simplicity's sake. After taking a few months hiatus from this, I returned ...

Having trouble hiding the message "Not found" with ng-hide and filters in AngularJS

I am currently working on incorporating instant search functionality with filters in AngularJS. My goal is to have the "Not Found!!" message displayed when the filter results in an empty array, indicating that no matches were found. However, I have encou ...

Merge JavaScript files from various folders using grunt's configuration settings

I am currently working with Grunt and Sass, and I am in search of a SASS-like feature that will allow me to import any JavaScript file I desire and merge them into a single file based on some configuration depending on the directory I am in. For instance, ...

Hiding javascript code within comment tags "<!-- //-->"

Years ago, I started a practice of enclosing all my JavaScript code in files with <!-- Code goes here //--> I'm not entirely sure why I did this. Maybe it was to hide the code from old browsers, is that right? Do I still need to do this? I ...

How come the subitems of a second-level nested list do not appear when hovering over a hyperlink?

Show "News" in French when hovering over the French option. ul#topmenu li a#HyperLink:hover ul { background-color: pink; display: list-item; } <ul id="topmenu"> <li class="langHorzMenu"> <a href="#" id="HyperLink">French</ ...

Is there a way to eliminate the # sign from hash data using jQuery?

Can anyone help me retrieve the hash value from the URL? var hash = window.location.hash; I am looking for a way to remove the "#" sign from the hash. Any suggestions? ...

What is the best way to store checkbox statuses in local storage and display them again in a JavaScript to-do list?

I'm currently working on a to-do list application using basic JavaScript. One issue I'm facing is saving the checked status of the checkbox input element and displaying it again after the page is refreshed. Since I'm still learning JavaScrip ...

What is the best way to perfectly center my CSS menu in a fluid style layout?

Can you assist me with this issue? I am trying to center my CSS menu precisely in the middle of the user's screen, both vertically and horizontally. Since users have varying screen resolutions, I need a fluid example to achieve this. Below is the HT ...

Including a drop-down arrow or triangle next to the initial button

In the navigation bar displayed below https://codepen.io/shaswat/pen/XzpRXL Is it possible to create a down triangle or arrow next to the "home" link, which changes direction upward when hovered over? How can this be achieved without modifying any HTML e ...

In AngularJS, when a user clicks on a specific element, the program should fetch the corresponding value from a separate dataset and display it

Hello, I am just starting out with angularjs and here is my current js file setup: angular.module("mainModule", []) .controller("mainController", function ($scope) { $scope.ProdMenu = [ {ProductMenuName: "CBS" ...

Utilize HTML to resize image to fit within container

I've encountered an issue while working with Adobe Dreamweaver CS5. I added a swap behavior to an image in an html document, expecting it to pop up at its original size and restore on mouse out. However, the swapped image ends up filling the entire sc ...

When an option is selected in one dropdown, a list is dynamically populated in another dropdown. However, the entire column then displays the selected row's options in a table format

https://i.stack.imgur.com/q7tMT.png Upon selecting an option from a dropdown within a table row, I make a call to an API to fetch a list of strings into another dropdown field for that specific row. However, the entire column is being populated with that r ...

What exactly is the significance of the </< in THREE.Camera.prototype.lookAt</<()?

After experimenting with THREE.js for a while, I came across something peculiar: When using Firefox and opening the developer console to type camera.lookAt (assuming your camera is named camera), it displays function THREE.Camera.prototype.lookAt</< ...

<div.content> </div.content> - Structure

I recall encountering this code before but I can't remember where: <div.main> // .... </div.main> <div.secondary> // .... </div.secondary> Could someone please clarify for me what this syntax is referred to as and what ...

Experiencing a snag with implementing Firebase version 9 FCM in Next.js 12

I decided to incorporate push notifications into my Next.js (version 12) app, so I integrated Firebase Cloud Messaging. Here is the implementation: import { initializeApp, getApp, getApps } from "firebase/app" import { getMessaging, getToken } fr ...