What is the best way to continuously run a series of functions in a loop to create a vertical news ticker effect?

I'm in the process of creating a vertical latest news ticker, and although I'm new to javascript, I'm eager to learn and build it myself.

So far, I've come up with this, but I want the news cycle to restart once it reaches the end.

    var latestNews = "February 2021 - Latest News for Feb";
    var latestNews2 = "January 2021 - Latest News for Jan";
    var latestNews3 = "December 2020 - Latest News for Dec";
    var latestNews4 = "November 2020 - Latest News for Nov";
    var latestNews5 = "October 2020 - Latest News for Oct";
    latestNewsFunction()

    function latestNewsFunction() {
        document.getElementById("latestNews").innerHTML = latestNews;
        document.getElementById("latestNews2").innerHTML = latestNews2;
        document.getElementById("latestNews3").innerHTML = latestNews3;
        document.getElementById("latestNews4").innerHTML = latestNews4;
        document.getElementById("latestNews5").innerHTML = latestNews5;
    }

    setTimeout(function(){
        document.getElementById('latestNews').className += ' hidden';
    }, 3000);

    setTimeout(function(){
        document.getElementById('latestNews2').className += ' hidden';
    }, 6000);

    setTimeout(function(){
        document.getElementById('latestNews3').className += ' hidden';
    }, 9000);

    setTimeout(function(){
        document.getElementById('latestNews4').className += ' hidden';
    }, 12000);

    setTimeout(function(){
        document.getElementById('latestNews5').className += ' hidden';
    }, 15000);
    .ln-container {
        border: 1px solid black;
        text-align: center;
        font-size: 16px;
        background-color: #eeeeee;
        height: 33px;
    }
    .lnln {
        list-style-type: none;
        font-size: 12px;
        margin: 0;
        height: 14px;
        overflow: hidden;
    }
    .hidden {
        display: none;
    }
<!DOCTYPE html>
<html>

<head>
    <title>Latest News Ticker</title>
</head>


<body>
    <div class="ln-container"><b><u>Latest News</u></b>
    <ul class="lnln">
        <li id = "latestNews"></li>
        <li id = "latestNews2"></li>
        <li id = "latestNews3"></li>
        <li id = "latestNews4"></li>
        <li id = "latestNews5"></li>
    </ul>
    </div>
</body>

If you have any ideas or suggestions, please share them. I'm still getting the hang of javascript, so my code may be basic right now, but I plan on improving with practice.

Answer №1

Organize your news updates in an array and cycle through them with a single element:

var latestNews = [
  "February 2021 - Latest News for Feb",
  "January 2021 - Latest News for Jan",
  "December 2020 - Latest News for Dec",
  "November 2020 - Latest News for Nov",
  "October 2020 - Latest News for Oct"
]
latestNewsFunction()

function latestNewsFunction() {
  let i = 0;
  setNews(latestNews[i])
  setInterval(() => setNews(latestNews[++i % latestNews.length]), 3000)
}

function setNews(news) {
  document.getElementById("latestNews").innerHTML = news;
}
.ln-container {
  border: 1px solid black;
  text-align: center;
  font-size: 16px;
  background-color: #eeeeee;
  height: 33px;
}

.lnln {
  list-style-type: none;
  font-size: 12px;
  margin: 0;
  height: 14px;
  overflow: hidden;
}

.hidden {
  display: none;
}
<div class="ln-container"><b><u>Latest News</u></b>
  <ul class="lnln">
    <li id="latestNews"></li>
  </ul>
</div>

Answer №2

I have devised this solution that incorporates a combination of clearTimeout and if statement to stop it. The setInterval function allows the loop to run every 3 seconds. I am relatively new to JavaScript, so there may be a more efficient solution out there. Enjoy!

    <div class="ln-container"><b><u>Fresh Updates</u></b>
        <ul class="lnln">
            <li id = "latestNews">February 2021 - Latest News for Feb</li>
        </ul>
    </div>


<script>   
    var news = {
        1: "February 2021 - Latest News for Feb",
        2: "January 2021 - Latest News for Jan",
        3: "December 2020 - Latest News for Dec",
        4: "November 2020 - Latest News for Nov",
        5: "October 2020 - Latest News for Oct",
    }
    latestNewsFunction()

    function latestNewsFunction() {
        // Start counter at 2 as the first is already displayed.
        var i = 2;
        setInterval(() => {
            document.querySelector("#latestNews").innerHTML = news[i];
            i++;
            // If on last news, reset
            if (i > 5) {
                i=1;
            }
        }, 3000);
    }
</script>

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

Choose various files (from various directories) using a single input type file element

Is it possible to select multiple files from different directories for the same input file type element using only HTML? I am aware of the multiple attribute, but it seems to only allow selecting several files at a time in the same directory within the b ...

Tips for adjusting font sizes within the same HTML header?

Looking to design an HTML header in the following format: "(10.3.4) Version1: vs (10.3.4) Version2:" Need the version numbers to be smaller than "Version1" and "Version2." Any ideas on how to achieve this? ...

UI-Router causing issues with AngularJS anchorScroll functionality

Currently, I am utilizing ui-router and attempting to implement automatic scrolling within the controller. However, it seems that anchorScroll function is not working as expected. My assumption is that it may be due to having two '#' symbols in t ...

What could be causing this minimal Angular - WebTorrent configuration to fail?

The setup appears to be quite straightforward. Check out the Webtorrent usage reference here This is how I have my setup: import WebTorrent from 'webtorrent'; @Component({ selector: 'app-root', standalone: true, template: `bla` ...

Hold off on running addThis

My website utilizes Google Maps along with my own JavaScript functions. Additionally, I am integrating the AddThis JavaScript for social sharing buttons. For optimal performance, I need both my custom JavaScript and Google's JavaScript to load and exe ...

Attempting to develop a next.js web application using Vercel has hit a roadblock for me. Upon running the "vercel dev" command in the terminal, an error message is

vercel dev Vercel CLI 28.5.3 > Creating initial build node:events:491 throw er; // Unhandled 'error' event ^ Error: spawn cmd.exe ENOENT at ChildProcess._handle.onexit (node:internal/child_process:285:19) at onErrorNT (nod ...

Passing values to the next page is not functioning as expected

I'm having trouble passing a variable called userId to the next page in my application. Below is the snippet of code I am using to pass the value to the next page: $.each($.parseJSON(data), function(key, value) { var userId = value.id_user; ...

Using ng-repeat with an AJAX-called JSON is not possible

I've been struggling with handling JSON data from an AJAX call and displaying it using ng-repeat. If you want to take a look at my code in a more organized way, I've shared it on http://jsfiddle.net/7quj9omw/. However, please note that the code ...

I am looking to implement user authentication using firebase, however, the sign-in page is currently allowing invalid inputs

<script> function save_user() { const uid = document.getElementById('user_id'); const userpwd = document.getElementById('user_pwd'); const btnregister=document.getElementById('btn-acti ...

Can you identify the attribute used for marking up an HTML code tag?

While examining a website's code to understand how they styled a specific section of their page, I came across the following snippet: <code markup="tt"> I thoroughly checked for any other references to this particular markup attribute ...

What is the best way to extract text from a class using selenium?

<div class="class-one"> <div class="class-two"> lorem ipsum <div class="class-three"> <a href="https://yahoo.com" target="" class="btn btn--primary btn--purple " id="" title="find"><i class="fal fa-fw fa-file-word"></i>& ...

Why is the button missing from the codepen?

I attempted to recreate the code from this Codepen link: https://codepen.io/jakaric/pen/mjJQvg However, unlike what you see here (in the run result), the liquid "Pretty little button" is not showing up in my local files. On Codepen, there is no library me ...

Print custom jQuery attribute to console or log output

I need help retrieving and displaying a custom jQuery attribute in either an alert or console. Despite attempting to use console.log() to access my custom data attribute, I am unable to see its value appear. The specific value I am trying to display is d ...

The image seems to be misaligned inside the DIV, and interestingly, this issue appears to be

http://jsfiddle.net/Bzpj4/ The situation depicted in the DIV above is quite puzzling. A 120x120 image is contained within a 120x120 DIV, which is then placed inside a larger DIV with a height of 120px. Strangely, the image within the larger DIV seems to b ...

`Generate JSON list`

How can I properly encode an array in PHP as JSON, ensuring it includes two variables? $var = 33; $last = 44; Here are the database results: foreach($query->result() as $r) { $data[]= $r; // Fills the array with results } I am attempting to cre ...

What is the best way to choose a single li element?

I am working on creating a reservation system using HTML, CSS, and JS. I want to customize the color of the border for each list item (li). However, I want only one li to be selected at a time. When I click on a different li, it should remove the selection ...

The WebView.HitTestResult method is currently only receiving <img src> elements and not <a href> elements

I am attempting to open a new window in the Android browser using "_blank". I have set up an event listener for this purpose. mWebView.getSettings().setSupportMultipleWindows(true); mWebView.setWebChromeClient(new WebChromeClient() { ...

Tips for updating the selected value in Vue dynamically

I am currently working on a feature where the months change dynamically based on the selection made using Vue. You can view the code snippet in the link provided below. <div id="app"> <span class="selectboxWrap"> < ...

Tips for personalizing error messages for the "required" field by utilizing a dictionary feature on VeeValidate in Vue.Js

I am trying to update the error message that appears when an input field with the "cpf" rule is left empty (meaning it does not meet the "required" rule). I believe using the "dictionary method" with custom messages is the solution, but I am struggling to ...

Centered HTML Columns on the Screen

Figuring out this simple html + css issue is proving to be quite challenging for me. I am attempting to create a '3 column' layout. I envision a central column (approximately 10em in width) with two additional columns flanking it on each side (e ...