Iterating through an array with conditional statements in JavaScript

I have recently joined this community and am new to coding. Unfortunately, I do not have anyone who can assist me with my issue. I have watched numerous YouTube videos in an attempt to solve the problem myself. I am working on looping through the array below using if-then and else statements along with the cardCounter function. My goal is to have each item in the array appear individually on the screen and then disappear one by one. However, when I open it in my browser, the array just appears as lines of text.

Here is the code I am currently using:

<script>
     const calm1 = [];
         calm1[0]= "Silence is the element in which great things fashion themselves 
          together. —Thomas Carlyle";
         calm1[1]= "Take a deep breathe in and count to 7 seconds ";
         calm1[2]= "Take a slow exhale out";
         calm1[3]= "Self-care is not selfish. You cannot serve from an empty vessel.– Eleanor Brown";
         calm1[4]= "Loneliness is a sign you are in desperate need of yourself.― Rupi Kaur,";
         calm1[5]= "do not look for healing at the feet of those who broke you― Rupi Kaur,";
         calm1[6]= "if you were born with the weakness to fall you were born with the strength to rise― Rupi Kaur";
         calm1[7]= "you kill your future by mourning the past― R.H. Sin";
         calm1[8]= "Our backs tell stories no books have the spine to carry― Rupi Kaur";
         calm1[9]= "what is stronger than the human heart which shatters over and over and still lives― Rupi Kaur";
         calm1[10]= "the world gives you so much pain and here you are making gold out of it- there is nothing purer than that― Rupi Kaur";
         calm1[11]= "fall in love with your solitude― Rupi Kaur";
         calm1[12]= "You do not just wake up and become the butterfly - Growth is a process.― Rupi Kaur";
         document.getElementById("calm").innerHTML = calm1;

     var words = document.getElementById('calm');
     var text = -1;
     function cardCounter () {
        text++;
        if (text<calm1.length) {
            words = calm1[text];
        }
        else {
            words = -1;
            clearInterval(intervalTimer);
        }

     ;}  
     var intervalTimer = setInterval(function(){cardCounter()},5000);

 </script>
 
 

Answer №1

If you're looking to update text in a div periodically, there are various methods to achieve this. Here's an example that you can follow:

const calmingQuotes = [
  "Silence is the element in which great things fashion themselves together. —Thomas Carlyle",
  "Take a deep breath in and count to 7 seconds ",
  "Take a slow exhale out",
  "Self-care is not selfish. You cannot serve from an empty vessel.– Eleanor Brown",
  "Loneliness is a sign you are in desperate need of yourself.― Rupi Kaur,",
  "do not look for healing at the feet of those who broke you― Rupi Kaur,",
  // more quotes here
];

let index = 0;

function setText(index) {
  document.getElementById("calm").innerText = calmingQuotes[index];
}

setText(index);

setInterval(() => {
  if (index + 1 == calmingQuotes.length) index = 0;
  else ++index;
  
  setText(index);
}, 5000);
<html>

<body>

  <div id="calm">

  </div>
</body>

</html>

Answer №2

The If/Then/Else construct is designed for decision making and does not support iteration over a collection of objects.

If you need to iterate through a list, you should use a loop such as a FOR loop.

Your function will resemble something like this. To make it more general, I have adjusted some variable names.

// Initialize the statements array
const phrases = [];
// Select the HTML element you wish to modify
const displayElement = document.getElementById('display');
// Create a time delay function that resolves after a specified number of milliseconds
const timer = ms => new Promise(resolve => setTimeout(resolve, ms))

// Define an asynchronous function that includes an awaited function call
async function phraseIterator(delay) {
  // Loop through each statement in the array and perform actions on them
  for(const phrase of phrases) {
    // Update the text property of the HTML element with the current statement
    displayElement.innerText = phrase;
    // Invoke the timer method we defined earlier to pause execution for a set duration
    await timer(delay);
  } 
}

You can now invoke your function whenever you want to begin cycling through the quotes

phraseIterator(5000);

Credit goes to this stackoverflow post for guidance on creating the timer functionality.

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

Problem with Bcryptjs Async Implementation

I have implemented a function in my node server using bcryptjs to hash and compare passwords. Here is the code snippet: this.comparePasswords = function(password1, password2, callback) { bcrypt.compare(password1, password2, function(error, result) { ...

The error callback in Jquery ajax is triggered despite receiving a 200 status code in the response

I am facing an issue with my ajax code. The success callback contains an alert that is not working properly. Here is the code snippet: $(".change_forex_transaction_status").click(function(){ $("#insufficient_funds").css("display","none"); var id = $( ...

Utilizing a single variable across different JavaScript scripts - where one script includes a .ready function while the other does not

I am facing a challenge with 2 javascript scripts that I have: <script type="text/javascript"> function capture(){ var canvas = document.getElementById('canvas'); var video = document.getElementById('video'); canvas.getContext ...

Utilizing Vue's v-for directive to manipulate data through custom looping

When I loop through my data using v-for, I find myself unsure of how to display the data with a custom looping method, such as using modulus. I aim to display the data in groups of three items, assigning a different class to every 3 items. The desired st ...

NodeJS: Issue with Route is disrupting the functionality of the Restful API

Struggling to develop an API using Node.js and Express, encountering routing issues with express.Router(). Take a look at my code below: Server.js file contents: // Get necessary packages var express = require('express'); var app = express(); ...

When working with an Angular application, IE9 may display the error message: "An internal error occurred in the Microsoft Internet extensions"

My application is encountering an issue in IE9: Error: A Microsoft Internet Extensions internal error has occurred. Error: Access is denied. When using IE's dev tools for debugging, the issue seems to be related to localStorage. if (localStorage) ...

Updating the Keycloak token in VueJS using keycloak-js even when it is still valid

I have implemented a VueJS frontend connected to Keycloak using keycloak-js openid, without using the implicit flow https://i.sstatic.net/BxhJh.png Currently, there is a scenario in which the Backend NodeJS adds groups to a user in Keycloak. However, in ...

Send out Chrome Desktop notifications to reach all users

I recently integrated Chrome Desktop notifications into my website by following the steps outlined in this helpful guide: Chrome desktop notification example After adding the script code to my site, I was able to get it working smoothly. However, I encou ...

Unable to close expanded grid item using close button

Currently, I am working on a simple 3 column grid where each grid item consists of an image and a close button. The functionality I want to achieve is that when a grid item is clicked, the image should expand and the close button should become visible. Th ...

A guide on incorporating unique font weights into Material UI

Looking to customize the Material theme by incorporating my own font and adjusting the font weights/sizes for the Typography components. I am attempting to set 100/200/300/400/500/600/700 as options for each specific typography variant, but it seems that o ...

jQuery efficiently handles large amounts of text data transfer (gradual loading)

The issue at hand: My website relies on jQuery AJAX (post) for navigation, meaning the page doesn't refresh every time a user moves to a different section. This setup requires me to fetch data using AJAX and present it dynamically. While this works w ...

What is the best way to confirm checkbox selection based on MySQL data?

Writing this question feels challenging, but I have a collection of checkboxes with their data stored as JSON in my PHP database. What I'm trying to achieve now is to dynamically load the JSON data on the page without refreshing it, checking specific ...

What is the best way to update object values only when changes occur, and leave the object unchanged if no changes

There is an object named ApiData1 containing key-value pairs, including color values within properties. The colors are updated based on the numberOfProjects value from ApiData2, with specific ranges dictating the color updates. This setup is functioning co ...

Tips on modifying the content of a Material UI Card

I have a Material UI card displaying some details, along with an 'Edit' button. When the Edit button is clicked, I want to update the content of the card within the same layout. Below is the code snippet: <Card className={classes.root} variant ...

How to trigger a jQuery function once a v-for loop has completed in VueJS?

Utilizing vue-resource, I successfully retrieve data from my API and incorporate it into my HTML. However, I am encountering an issue where I want to execute a jQuery function after the v-for loop has completed in order for jQuery to recognize elements in ...

Uploading files with Vue.js Element-UI and axios triggers unwanted page refresh

I am utilizing the element-ui file upload component() to manage the frontend of image uploading. All functionalities work flawlessly (file is successfully sent to the server, etc). However, for some reason, after the axios's successful response code r ...

What is the process for displaying a list of all files within a folder?

I'm currently working on a project where I have a 'products' directory located in the same folder as my index.html file. My goal is to develop a script that can tally all the jpg files within the 'products' folder and then generate ...

Issues with reactivity are present in certain items within Vue.js cards

Can someone please assist me with this issue that has been causing me trouble for days? I am working on updating the quantity and total price in a checkout card: The parent component: <template> <div> <upsell-checkout-product ...

Ways to extract text from a temporary element

Here is my HTML code: <div class="p-login-info" ng-show="loggedOut()">My text.</div> This is the corresponding JavaScript code: var e = element(by.className('p-login-info')); e.getText() .then(function(text){ var logoutText = ...

Error with the Knockout framework's inability to bind to the model

I seem to be encountering an issue with binding Knockout to a model in my code. Despite the code firing and returning a JSON object, the table appears empty. Any advice or suggestions would be greatly appreciated. HTML <table style="border: double"& ...