Loop through the JavaScript array and continuously display the last item in the array. Repeat this process indefinitely

I am working on a code to create a "fade-In fade-Out" effect for text. However, I'm facing an issue where the text displayed is always the last value in the array instead of changing to the next one each time it fades in and out.

Here is the HTML code below:

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function(){
    var str = $("#string").text().split(' + ');
    setInterval(function(){
        s++;
        for (var s = 0; s < str.length; s++) {
            var string = str[s];
            $("#string").html(string);
            $("#string").fadeIn(500);
            $("#string").fadeOut(3000);
        }   
    }, 6000);
});
</script>
</head>
<body>
<p id="string" style="display:none;">Name 1 - Message 1 + Name 2 - Message 2 + Name 3 - Message 3</p>
</body>
</html>

Thank you!

Answer №1

Instead of using a loop, you can achieve your desired outcome in a simpler way:

var placeholder = $("#string");
var words = placeholder.text().split(' + ');
var index = 0;
window.setInterval(ShowCurrentWord, 6000);
ShowCurrentWord();
function ShowCurrentWord() {
    var currentWord = words[index];
    placeholder.html(currentWord).fadeIn(500).fadeOut(3000);
    index = (index + 1) % words.length;
}

Check out the live test case here.

Here's a tip: keep track of the current index using a global variable and increment it in each function execution. Don't forget to call the function initially to avoid waiting for 6 seconds before the first item appears.

Answer №2

Your current code is causing the last item to be displayed every time because the loop is inside the timer.

To fix this issue, you should replace your code with the following:

$(document).ready(function(){

    var str = $("#string").text().split(' + ');
    var s = 0;
    var arrayLength = str.length;

    setInterval(function(){

        if(s>(arrayLength - 1)){
            s = 0;
        }   
        var string = str[s];
        $("#string").html(string);
        $("#string").fadeIn(500);
        $("#string").fadeOut(500);

        s++;

    }, 1000);
});

You can view the updated code on JSFiddle here: http://jsfiddle.net/zGSYz/

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

Updating a data table using POST values in ASP.NET: A step-by-step guide

I am working on updating values in my database and want to ensure that my script is functioning correctly. In order to check, I created a POST method to send the values and confirm they are being received. https://i.sstatic.net/h0IH5.gif Now, my question ...

Extracting information from a string with JSON in Javascript

Can you assist me? I have developed a web service that provides a clean string after clicking on the URL: { "PersonID": 125, "Title": "Security Officer", "Company": "TSA", "CellNum": "423-915-3224", "EmergencyPhone": "", "Email": " ...

Encountering a MODULE NOT FOUND error when using express.js

const express = require("express"); const app = express(); const path = require("path"); app.use(express.static(staticPath)); let staticPath=path.join(__dirname, ".."); There seems to be an error in these lines of ...

Having trouble getting Google Tag Manager (GTM) to function properly on SharePoint?

I inserted the GTM code within the SharePoint Master Page body tag. <body> <--Body content goes here --> <!-- Google Tag Manager --> <noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-XXXXXXXX" he ...

Guide to locating and substituting two integer values within a string using JavaScript

Given a string such as: "Total duration: 5 days and 10 hours", where there are always two integers in the order of days and then hours. If I need to update the old string based on calculations using fields and other values, what is the most efficient meth ...

Delete the span element if the password requirements are satisfied

I am implementing password rules using span elements. I aim to dynamically remove each span that displays a rule once the input conditions are met. Currently, I have succeeded in removing the span related to the minimum length requirement but I am unsure h ...

Is there a way to continually update a specific portion of a webpage using AJAX without manual intervention?

$messages = $db->query("SELECT * FROM chatmessages ORDER BY datetime DESC, displayorderid DESC LIMIT 0,10"); while($message = $db->fetch_array($messages)) { $oldMessage[] = $message['message']; } $oldMessages = array_reverse($oldMessage ...

Is there a way to organize items in an array alphabetically according to a predetermined key value?

I have an array of objects containing countries with various values for each country. My goal is to list them alphabetically. // globalBrands { [ { id: 1, title: 'Argentina', content: [{url: 'w ...

Struggling to adjust the dimensions of a React Barcode to the specified width and height?

I've encountered an issue with resizing the React Barcode Image. I prefer all barcodes to have a width of 200px and a height of 100px. From what I understand, the width of the barcode will expand when the length value increases. Below is my current co ...

What is the best way to retrieve the 'date,time' column from a MySQL database and use it as input for the google chart DateRangeFilter?

I am facing an issue with a column in my dataset that contains date-time values, such as '2017-2-2 10:30:20'. I need to use these rows as an input for a Date Range Filter in Google Chart. Can someone guide me on how to achieve this? I attempted ...

When arriving on a page via an HTML anchor tag, the CSS style does not appear. How can I "reinstate" it?

I have set up a website with an index.html page that links to a contact.html page using anchor tags. On the contact.html page, there are anchor tags that should navigate the user back to specific sections of the index.html page. The navigation works fine, ...

Preserving the button's state when clicked

Here is my code snippet: <blink> const [thisButtomSelected, setThisButtomSelected] = useState(false); var thisButton = []; const onAttributeClick = (e) => { thisButton[e.currentTarget.value] = { thisID: e.currentTarget.id, thisName: e. ...

Tips on separating a function into two separate files in Node.js

Hey there! I am just starting to explore Node.js so bear with me if I make any mistakes. So, I have this file: exports.Client = function() { this.example = function(name, callback) { console.log(name); }; ...

Using PHP, create a redirect page that utilizes AJAX and jQuery for a seamless user experience

My goal is to navigate from page a to the profile page with a post session in between. Let's assume that the data is stored in a variable called $name as a string. The current code on page a looks like this: jQuery("#result").on("click",function(e){ ...

Adjusting table column widths in Bootstrap 4

I am completely new to bootstrap and am in the process of enhancing an existing MVC web application that is already utilizing bootstrap 4. My goal is to incorporate a table with form fields, but I am facing difficulties in controlling the column widths of ...

Obtaining API/JSON Data to Implement in a NextJS Application

Currently, I am working on developing a NextJs website that focuses on detecting crop diseases. The process involves sending photos and environmental data to a fastapi python server for processing. Subsequently, the processed data is supposed to be display ...

Create a new one-dimensional array by stacking the columns of a matrix

In my current project, I am dealing with a complex array of arrays where each inner array contains objects. My goal is to transform this multidimensional array into a flat array organized in a column-wise order. Here is the code snippet that I have implem ...

Exploring the process of using querySelector() to locate specific class and div IDs in JavaScript code

My objective is to make the id="myDropdownTop" trigger the corresponding drop-down menu. The problem lies in my script code, particularly the final line: ("div.dropdown-content").classList.toggle("show"); does not seem to be functioning correctly. <!D ...

Arranging alphanumeric values in JavaScript or jQuery

There is some data in a select field as shown below: 72A(6) , 72(A)(6A) , 78(1) , 72AB(1) , 79 , 80QQB , 80RRB , 80TTA , 80U , 80CCC , 80CCD , 80CCE , 80CCF , 80CCG , 80D , 80DD , 80DDB , 80E , 80EE , 80G , 92C(4) , 80G(2)(c ) , 80G(5) , 80GG , 80C , 80GG ...

Turn off any :hover CSS effects that are present when viewing on a separate media

Is it possible to disable hover effects on a specific CSS element during Print Preview and when printing a page? For example, if I have the following code: .this-thing:hover { /* something magical */ } I want to prevent the hover effect defined in .thi ...