Navigating through the options list and returning to the top for a fresh start: a simple guide

I'm looking for a way to make a list of 5 elements automatically scroll through each one every 3 seconds. Once it reaches the last element, I want it to loop back and start again from the first element. Here is what I've tried so far.

var height = $(".list li:first-child").outerHeight();
    
setInterval(function(){ 

        $('.list').animate({
            scrollTop: 58
        }, 500);

}, 3000);
.list{width: 200px;height: 180px;overflow: auto;list-style: none;padding-left: 0px;}
ul.list li{padding:20px 0px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<ul class="list">

    <li>Option 01</li>
    <li>Option 02</li>
    <li>Option 03</li>
    <li>Option 04</li>
    <li>Option 05</li>

</ul>

Currently, the list only scrolls to the second element and then stops. Can anyone suggest a solution to fix this issue?

Your assistance would be greatly appreciated.

Answer №1

Your code currently has a fixed scroll value of 58, causing it to scroll down by that amount and then stop.

To resolve this issue, you should implement a scrolling mechanism that involves scrolling down by 58, waiting for 3 seconds, then scrolling down by another 58 units. Once you reach the bottom (after 2 scrolls totaling 116), reset the scroll value to 0 to scroll back up.

Below is the updated code snippet:

let scrollValue = 0
setInterval(function(){ 
        scrollValue < 116 ? scrollValue += 58 : scrollValue = 0;
        // console.log(`scrollValue: ${scrollValue}`);
        $('.list').animate({
            scrollTop: scrollValue
        }, 500);
}, 3000);
.list{
    width: 200px;
    height: 180px;
    overflow: auto;
    list-style: none;
    padding-left: 0px;
}
ul.list li{
    padding:20px 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<ul class="list">
  <li>Option 01</li>
  <li>Option 02</li>
  <li>Option 03</li>
  <li>Option 04</li>
  <li>Option 05</li>
</ul>

In this revised code, a variable scrollValue is used to control the scrolling behavior. The value starts at 0 and increments by 58 with each animation call. When the total reaches 116 (after two scrolls), it resets to 0 for upward scrolling.

Answer №2

In order to achieve this, you will need to determine the number of items you have and utilize the height of the item that you have identified but not utilized yet. You will then need to keep track of the current count/step and increment it as long as it is less than the total length of items, or reset it to 0 if it exceeds.

However, a challenge arises when no scrolling occurs for items near the bottom because there is no space left for the container to scroll. One potential solution is to create additional space for scrolling by adding space below the last li element, although this may result in an unconventional appearance.

var height = $(".list li:first-child").outerHeight();
// Determine the number of items
var itemLength = $(".list li").length
// Set currentItem to 0
var currentItem = 0
// Initialize scroll to height so that the first interval goes to item[1]
var scroll = height

setInterval(function() {

  $('.list').animate({
    scrollTop: scroll
  }, 500);
  // Increment the step or reset to 0 if it exceeds the length of items
  if (currentItem < itemLength - 1) {
    currentItem ++
  } else {
    currentItem = 0
  }
  // Update the scroll based on the changes above
  scroll = currentItem * height

}, 3000);
.list {
  width: 200px;
  height: 180px;
  overflow: auto;
  list-style: none;
  padding-left: 0px;
}

ul.list li {
  padding: 20px 0px;
}
li:last-of-type {
margin-bottom: 150px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<ul class="list">

  <li>Option 01</li>
  <li>Option 02</li>
  <li>Option 03</li>
  <li>Option 04</li>
  <li>Option 05</li>

</ul>

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

Validating file uploads using JQuery

I have been struggling to transfer a file from ajax to php for some time with no luck. That's why I decided to use JQuery Validate Within my form, there are multiple inputs such as name and email, along with one input of type file. I am able to valid ...

jQuery: The duration parameter does not work in the .animate() function

My attempts to adjust the duration parameters in the code below (50, 1000, 4000) seem to be ineffective. Regardless of the duration value I set, the animation appears to run at a speed that is approximately half a second. For a live demonstration, please v ...

Utilizing Cordova and AngularJS to efficiently retrieve JSON data through XMLHttpRequest in a factory

I've encountered an issue while attempting to retrieve a JSON from an API using XMLHttpRequest within a factory. Despite the debug logs suggesting that everything is functioning correctly, I keep getting an "undefined" response. Below is the code for ...

Unexpected failure in WebdriverWait despite the presence of the element

Below is the code snippet in question: def CheckQueue(driver): qdone = False qID_xpath_start = "/html/body/div[5]/form/table/tbody[1]/tr[" qID_xpath_end = "]/td[2]/a" qIDindex = 1 while not qdone: print "enter loop" pri ...

Struggling with a character entity in Javascript? Learn how to escape it and avoid any display issues (such as showing

document.title = ("welcome &rarr; farewell"); Trying to display the arrow symbol "→" but it's not showing correctly. Any tips on how to properly escape it? ...

MultiArray authentication system

I am currently working on a multi-array login system, but I am facing an issue where only the first account is functioning properly. The other two accounts are displaying incorrect password or username errors. Account 1 corresponds to the name, Account 2 ...

Effortless transition of z-index on click using jQuery

I have created a script that successfully changes the z-index of a div when a button is clicked. However, the transition happens too quickly and I would like to add a smooth fade-out animation. Can anyone help me with this? $("#card").click(function(){ ...

Transform the JavaScript function to a Node.js module

My function serves as an abstract factory for creating JavaScript objects. Here is the code: var $class = function(definition) { var constructor = definition.constructor; var parent = definition.Extends; if (parent) { var F = function ...

The styling in CSS does not accurately reflect its relationship to the parent

My code includes a div with the ID of "outer" nested inside a parent div with the ID of "Container". I'm attempting to adjust the properties of the outer div relative to its parent, meaning its width, height, and other attributes should be based on th ...

In Firefox, the use of jQuery to disable the middle click feature on the mouse is

Can someone assist me with disabling the middle mouse click on a link using the code below? $(selector).on('click', function(e) { if(e.which == 2) { e.preventDefault(); } }); This code works well in Chrome, but unfortunately it& ...

Is the side tab overflowing the window due to its absolute positioning?

My browser window has a side tab that slides in when clicked using jQuery. The issue I'm facing is that the tab overflows the body due to its absolute positioning. However, the overflow stops when the tab is pulled in by jQuery. It only happens when t ...

Node.js and Azure blob storage compliment each other perfectly

After utilizing Azure DB for some time, I encountered an issue where I couldn't store large files in Azure. As a workaround, I discovered Storage Account. I have been using tedious (JS) to make queries. Is it possible to save and retrieve data using ...

Maintaining Element Position in Responsive Design when Window is Resized Using Absolute Positioning Inside Relative

I have 2 div elements. The first div is larger and has the position:relative property. The second div contains a set of boxes inside the first div and has the position:absolute property. As I resize the window to make it responsive, the height of the se ...

Creating a structured paragraph using nested labels and v-selects in Vue.js (with Vuetify and Pug)

I am looking to create a paragraph that includes text and options presented in dropdown lists. While I have made some progress, I am facing challenges with the design aspect as it needs to be formatted in a specific manner: Lorem ipsum dolor sit amet, [ D ...

Can we dynamically generate CSS classes when defining them in HTML5?

Is there a possibility to assign a value for a specific attribute when defining a class in a way such as this: <div class='padding-l-10'> ----------------*code here*------------------- </div> .padding-l-X { padding-left: X; } ...

ts-jest should replace the character '@' with the '/src' folder in the map configuration

I have set up a node project using TypeScript and configured various paths in my tsconfig.json file, such as: "paths": { /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl' ...

What is the best way to implement dynamic comment display similar to Stack Overflow using Asp.net and Jquery?

I have created a small web application using Asp.net and C#. Currently, I am able to retrieve comments by refreshing the entire page. However, I would like to achieve this functionality without having to do a full refresh. For instance Let's say the ...

Creating an arc within a polyline in THREE.JS

My data consists of the following points: "POLYLINE":[[ {"x":"-6094.1665707632401","y":"3074.764386330728","r":""}, {"x":"-699.22595358468595","y":"1099.941236568309","r":""}, {"x":"-4940.397089330264","y":"576. ...

The MathJax system is currently unable to process LaTeX environments

Currently, I am in the process of creating a blog post on Blogspot. Here is the MathJax configuration that I have integrated into the theme's HTML file: <script defer='defer' id='MathJax-script' src='https://cdn.jsdelivr.ne ...

Updating the default color of selected text within a webpage's content

Is there a way to modify the default blue color that appears when content is selected on a webpage? I am wondering how to change this selection color to a custom color of choice. ...