Looking for the optimal method to display numerous lines of text in HTML, one by one, at intervals of 60 seconds?

I'm working on a display page for my website.

The main text in the center needs to change every 60 seconds.

I have over 150 individual lines of text that I want to cycle through on the page.

What would be the most efficient way to load all these text lines?

Should I load them one by one or from another file?

I just want to find the best way to handle loading the text smoothly.

var divs = $('div[id^="content-"]').hide(),
  i = 0;

(function cycle() {

  divs.eq(i).fadeIn(2000)
    .delay(60000) // 1000 is 1 second
    .fadeOut(2000, cycle);

  i = ++i % divs.length;

})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content-1">text 1</div>
<div id="content-2">text 2</div>
<div id="content-3">text 3</div>
<div id="content-4">text 4</div>
<div id="content-5">text 5</div>
<div id="content-6">text 6</div>
<div id="content-7">text 7</div>
......
<div id="content-180">text 180</div>

Answer №1

A single text element can be used to cycle its content on a 1-second interval. The code includes a modulus operator to ensure the array cycles properly.

To stop the cycling, the code allows for setting the function as a variable and using clearInterval(variable).

While the fade animation is not included in the code provided, it can easily be incorporated.

var content = ['This is text content 1',' This is another text  content', 'I am also a text content']; 
let contentLength = content.length;
let count=0;

function contentDisplay (){
   document.querySelector('#content').innerText = content[count % contentLength];
  count++;
}

// sets the initial display
contentDisplay();

// sets the interval to change the display
setInterval(contentDisplay, 1000);
#content {
  text-align: center;
  padding: 15px;
  font-size: 20px
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="content">text 1</p>

Answer №2

async/await is a great programming pattern.

var arr = ["apple", "orange", "banana"];

function twoSeconds() {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve('resolved');
        }, 2020);
    });
}
async function displayFruits(arr) {
    console.log("Beginning to display fruits");
    for (var i = 0; i < arr.length; i++) {
        await twoSeconds();
        console.log(arr[i]);
    }
    console.log("All fruits displayed.");
}
displayFruits(arr);

Answer №3

It's surprising how little 150 lines of text is for today's browsers, even on tiny mobile screens. One neat trick is to store the text in javascript and repeatedly populate a single div with it, rather than cluttering up the DOM with multiple divs.

var lines = [
    "Text line 1",
    "Text line 2",
    "etc"
];

var div = $('div[id="content"]');
var i = 0;

(function cycle() {

  div
    .text(lines[i])
    .fadeIn(2000)
    .delay(60000) // 1000 is 1 second
    .fadeOut(2000, cycle);

  i = ++i % lines.length;

})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content"></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

Implementing three identical dropdown menus using jQuery and HTML on a single webpage

It seems like I've tangled myself up in a web of confusion. I'm trying to have three identical dropdowns on a single page, each displaying clocks from different cities (so users can view multiple clocks simultaneously). However, whenever I update ...

Issue with JQuery mobile: dynamically inserted popup fails to appear

Can you help me troubleshoot an issue with my function? It's supposed to take a text string and output the text surrounded by '¬¬¬' in a button with a pop-up menu attached. The button looks fine, but when clicked, the popup ul list doesn& ...

Is the contenteditable feature working properly when updating PHP, SQL, and AJAX in the network?

Struggling with updating modified text to SQL using PHP and Ajax. Unsure if the issue lies in the data sent through Ajax or a problem within the PHP script. Below is my snippet from the HTML file: <tr> <td class="editingTab" contenteditable=&ap ...

Unable to load the threejs module

I am still learning about threejs and have mostly worked on projects using a dev server (vite) locally. This setup limited me to accessing my projects only from the browser on my computer. Here is how I typically include my files in these projects: <bod ...

jQuery: use the "data-target" attribute to toggle the display of a single content area

My code generally works, but there is an issue. When clicking on "Link 1" followed by "Link 2", only the content for Link 2 should be visible. How can I achieve this with my code? $("li").click(function() { $($(this).data("target")).toggle(); // ...

How can I bind the ID property of a child component from a parent component in Angular 2 using @Input?

I have a unique requirement in my parent component where I need to generate a child component with a distinct ID, and then pass this ID into the child component. The purpose of passing the unique ID is for the child component to use it within its template. ...

Avoid altering the Vuex store state directly without using mutation handlers in VueJS

I am currently working on developing a listenAuth function that monitors the "onAuthStateChanged" event in firebase to inform the vuex store whenever a user logs in or out. From what I can gather, I am only updating state.authData using the mutation handle ...

The Oracle Apex Login Interface with a Touch of Customized Styling

Currently, I'm working on creating a login page in Oracle APEX. While modifying the icon using CSS code, everything seems to be falling in place except for this one particular line: .t-Login-logo { background-image:url(#APP_FILES#LogoUpdated.jpg); bac ...

Traversing a JavaScript class within a for loop

I am attempting to access the locations listed in json.responseJSON.Sites, starting with LHR on the first iteration and then NJE on the next one, and so forth. The notifications for each location are "LHR" and "NJE", respectively. Is it possible to achieve ...

What is the best way to customize multiple checkboxes in React Native?

I need help with implementing checkboxes in my app using react-native-check-box. I have tried creating 4 checkboxes, but the text inside them is not aligning properly. The boxes are rendering one above the other instead of staying on the same line. I want ...

Leveraging a VueJS prop as a variable in an array mapping operation

Trying to figure out a solution where a variable (prop) can be used in an array map function. The initial code snippet looks like this: var result = this.$store.getters['example/store'].map(a => a.fixed_column) I aim for fixed_column to be ...

Styling on Material UI Button disappears upon refreshing the page

I've been using the useStyles function to style my login page, and everything looks great except for one issue. After refreshing the page, all styles remain intact except for the button element, which loses its styling. Login.js: import { useEffect, ...

Ensuring the Selection with jQuery

I've successfully implemented jQuery validation on a text field, but when I try to apply it to a radio button, it doesn't seem to work. I'm not sure what I'm doing wrong. Here is my HTML and jQuery code: <input type="text" placehol ...

Javascript Flickering Effect in HTML5

Currently, I am in the process of creating a simple game using javascript without jQuery. However, I am facing an issue with flickering on the canvas due to the clearing command. After researching solutions online, I came across suggestions for implementin ...

The validation for Australian mobile numbers should include the option to have spaces between the digits

How can I validate a mobile number properly? The first text input should start with 04 It should have a total of 10 digits, including 04 (e.g. 0412345678) Below is my input field: <form name="uploadForm"> <input type="tel" name="MobileNumber" ...

What is the best way to adjust the color of the colon within my timer digits using a span element?

I am facing an issue with my timer where the span that was created to display a colon between the numbers does not change color along with the timer digits. I attempted using var colon = document.getElementById(":"); but it still did not work as expected. ...

Encountering unexpected fetch requests to JSON files when using getStaticProps/getStaticPaths

My webpage seems to be functioning correctly, however I have noticed that in the console there are 5, 404 errors appearing on fetch requests. It's puzzling where these errors are originating from. Interestingly, these 404 errors only occur in the pro ...

How can an object inside an array be destructured in just one line?

Consider the following array: const array = [{b:2}] Can you extract the value of b using destructuring in just one line? I attempted something similar to this approach, but it did not yield the desired result: const [{b} = array] ...

Learn the technique of swapping out a portion of a string with a value from an input field in real-time

My webpage has a form on the left side where users can input text, and on the right is some static text. I want the text on the right to update automatically as the user types in the input field on the left. In my HTML code, it looks something like this - ...

Is it acceptable to compare a boolean with a string?

In my code, I have a variable called isRefreshed which is initially declared like this: var isRefreshed = ''; Sometimes, in certain scenarios, isRefreshed can be assigned a boolean value, for example: isRefreshed = false; Now, there is an if ...