Is there a way to dynamically update the content of <li> tag with values from an array every x seconds

I am trying to create a li list using jQuery that will update every 2 seconds with new content, similar to game news updates. However, I'm encountering an issue during the first cycle where it skips the second item in the array. The subsequent cycles work as expected.

Below is my current code:

$(document).ready(function() {
            var pages = ["<li class='active'><a href='#'>Hello</a></li>", "<li class='active'><a href='#'>Hello2</a></li>", "<li class='active'><a href='#'>Hello3</a></li>"]
var index = 0;
    setInterval(function() {
        $("#ul_news").empty().append(pages[index]);
        index++;
        if (index >= pages.length){
        index = 0;
        }
        setInterval(function(){
        $(".active").empty().append(pages[index]);
        }, 2000);
    }, 2000);

});
#ul_news{
position: absolute;
top: 0;
left:100px;
z-index: 20;
}
#ul_news li{
z-index: 20;
color: black;
list-style: none;
padding-bottom: 50px;
}
.non_active{
z-index: -1000;
}
<!DOCTYPE html>
<html lang="cs-cz">
<head>
<meta charset="UTF-8>
<title>Document</title>;
<meta name="viewport" content="width=device-width" />
<link rel="stylesheet" href="index.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="script.js" type="text/javascript"></script>
</head>
<body>
<ul id="ul_news">
<!--<li class="active"><a href="#">ahoj2</li>
<li class="non_active1">ahoj3</li>
<li class="non_active2">ahoj4</li>
<li class="non_active3">ahoj5</li>-->
</ul>
</body>
</html>

Answer №1

It seems there may be some confusion between setInterval and setTimeout

Unlike setTimeout, which executes a function once after a specified time delay, setInterval repeats the execution of a function unless explicitly stopped with clearInterval(). In the provided example code, you can see how setInterval is used to cycle through an array of pages:

var pages = ["<li class='active'><a href='#'>Hello</a></li>", "<li class='active'><a href='#'>Hello2</a></li>", "<li class='active'><a href='#'>Hello3</a></li>"]
var index = 0;
// just a bit of caching:
var news = $("#ul_news");
setInterval(function() {
  news.html(pages[index]);
  index++;
  if (index >= pages.length){
    index = 0;
  }
}, 2000);
<!DOCTYPE html>
<html lang="cs-cz">
<head>
<meta charset="UTF-8>
<title>Document</title>
<meta name="viewport" content="width=device-width" /&
<link rel="stylesheet" href="index.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="script.js" type="text/javascript"></script>
</head>
<body>
<ul id="ul_news">
<!--<li class="active">ahoj2</li>
<li class="non_active1">>ahoj3</li>
<li class="non_active2">>ahoj4</li>
<li class="non_active3">$gt;ahoj5</li>$gt;
</ul>
</body>
</html>


Additionally, instead of using .empty().append(), you can achieve the same result using just the html() method.

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

Bottom-aligned footer that remains in place instead of sticking to the page

I am attempting to position a footer at the bottom of the page, without it being sticky. Instead, I want it to remain at the bottom in case the user scrolls down there. Although it technically "works," there appears to be some white space below the footer ...

Tips for Customizing the Appearance of Material UI Select Popups

My React select component is functioning properly, but I am struggling to apply different background colors and fonts to the select options. https://i.stack.imgur.com/kAJDe.png Select Code <TextField fullWidth select size="small" nam ...

Reposition the checked box to the top of the list

My goal is to click on each item, and the selected item should move to the top of the list and be rendered at the top. However, I encountered an issue where when clicking on an item, it moves to the top but the item that replaces it also gets checked. Bel ...

Is it possible to maintain the width of an element even when its height is set to 0px?

Let me provide a detailed explanation of my issue below, but the question remains the same: Is there a way to make an element hidden or invisible with a height of 0px or slightly more than 0px while maintaining its width for functionality in Safari? Here ...

Encountering a Circular JSON stringify error on Nest.js without a useful stack trace

My application is being plagued by this critical error in production: /usr/src/app/node_modules/@nestjs/common/services/console-logger.service.js:137 ? `${this.colorize('Object:', logLevel)}\n${JSON.stringify(message, (key, value ...

The EJS is causing a problem with linking the style sheet

Currently, I am in the process of familiarizing myself with ejs, express, and node js. Facing an issue while trying to link my style sheet to my header, below is the code snippet and here is a https://i.stack.imgur.com/0BEIn.png. Utilizing include for bo ...

What are some ways to personalize a scrollbar?

I am looking to customize the scrollbar within a div. I attempted to modify it using the code below, but I encountered difficulties when trying to change the scroll buttons and did not achieve my desired outcome. Additionally, this customization did not wo ...

Protractor: How to Handle Multiple Browser Instances in a Non-Angular Application and Troubleshoot Issues with ignoreSynchronization

I have encountered an issue while using protractor to test a Non-Angular application. After implementing the browser.forkNewDriverInstance(), it appears that this function is no longer functioning correctly as I am receiving the following error message dur ...

What are some strategies for customizing the appearance of child components within a parent component?

I have a scenario where I am using parent and child components. When I use the HTML in another component, I also apply my CSS. For example, in my parent component: HTML <div class="chips"> <p class="tags">Tag 1</p&g ...

The webpage is missing a rendered React component even though it should be displayed

I am facing an issue where a React component is not appearing on the webpage despite being rendered. I have provided the code and screenshots of the components below for reference. Below is the snippet from the "App.jsx" file: function createCard ...

Ensure success when utilizing laravel's ORM for deletion

I have a table set up with a link to delete specific tasks @foreach ($tasks as $task) <tr> <td>{{$task->id}}</td> <td>{{$task->name}}</td> <td><a href="javascript:void( ...

Can an image be resized to fill either the full height or width based on its orientation?

Looking to display a dynamic list of images with varying sizes and orientations - some landscape, some portrait. The challenge is that the landscape images should fill 100% width of their parent container, while the portrait images should fill 100% height ...

Troubles with Angular Js: Issues with using $http.put with absolute URLs

Having an issue with $http.put in AngularJS. My server is built with Node.js and my app is in AngularJS. I am trying to make requests from AngularJS to access data on the Node.js server (same host). This code works: $http.put("/fraisforfait", elements); ...

Unable to retrieve a string from one function within another function

Three functions are responsible for triggering POST API calls, with the intention of returning a success or failure message to whoever invokes them (Observable<string>). In an effort to avoid repetition, I introduced a new function to retrieve succe ...

Passing the output of a function as an argument to another function within the same HTTP post request

I have a situation where I am working with two subparts in my app.post. The first part involves returning a string called customToken which I need to pass as a parameter into the second part of the process. I'm struggling with identifying where I m ...

"Triggering an AJAX POST request with a click event, unexpectedly receiving a GET response for

Hello there! I am currently attempting to send an AJAX POST request when a button is clicked. Below is the form and button that I am referring to: <form class="form-horizontal" > <fieldset> <!-- Form Name --> <legend> ...

How to retrieve document.getElementsByName from a separate webpage using PHP and javascript

Hey there, I've been searching for a solution to this issue but haven't had any luck so far. I'm attempting to retrieve the value of the name test from an external website. <input type="hidden" name="test" value="ThisIsAValue" /> Up ...

Error encountered while using JavaScript for waiting in Selenium

When using selenium and phantomjs to submit a form and then navigate back to the previous page, sometimes I encounter a timeout error as shown below: TimeoutError: Waiting for element to be located By(xpath,//div[@id='ContactFormBody']/div/br) W ...

Content moves as you scroll, not within a lightbox

I have implemented lightbox style overlays for my 'Read More' content on my website. However, I am facing an issue where the content within the lightbox does not scroll; instead, the background page scrolls. Any assistance with resolving this p ...

Three Divisions Positioned at the Top, Middle, and Bottom

I need to place 3 divs at the top, middle, and bottom positions. To achieve this, I have used jQuery to calculate the viewport height and apply a percentage of it to the top and bottom divs. However, resizing the page causes issues as the middle div overl ...