What is the best way to utilize my function across several different elements?

I'm having trouble applying my function to multiple elements. My goal is to have each element change individually on its own.

Currently, only the first element is changing. I want all three of them to change separately.

For instance:

Not Available

Available

Available

var updateVar = setInterval(updateStatus, 2000);

function updateStatus() {

  var status = Math.random();

  if (status < 0.90) {
    str = "Available";
    message = str.fontcolor("green");
    available = true;
  } else {
    str = "Not Avaliable";
    message = str.fontcolor("red");
    available = false;
  }

  var elements = Array.from(document.querySelectorAll('.demo'));
  for (const elem of elements) {
    elem.innerHTML = message;
    break;
  }
}
<p id="demo1" class="demo"></p>
<p id="demo2" class="demo"></p>
<p id="demo3" class="demo"></p>

Answer №1

Try moving the random number generation inside the for loop and eliminating the break statement. I've also adjusted the probability threshold from 0.9 to 0.5 for better results.

var myVar = setInterval(breakdown, 2000);

function breakdown() {

  let elems = Array.from(document.querySelectorAll('.demo'));
  for (const elems1 of elems) {
    let d = Math.random();

    if (d < 0.50) {
      let str = "Available";
      text = str.fontcolor("green");
      x = true;
    } else {
      let str = "Not Available";
      text = str.fontcolor("red");
      y = false;
    }
    elems1.innerHTML = text;
  }
  
}
<p id="demo1" class="demo"></p>
<p id="demo2" class="demo"></p>
<p id="demo3" class="demo"></p>

Answer №2

Your use of the break statement within the loop is causing it to exit prematurely without iterating over all elements. To address this, I have moved the loop to the top of the function based on your comments ('Available', 'Not available', 'Not available'). Additionally, the invocation of Array.from seems unnecessary in this context.

I suggest considering an alternative looping method such as forEach.

var myVar = setInterval(breakdown, 2000);

function breakdown() {

  var elems = document.querySelectorAll('.demo');
  for (const elem of elems) {
  
    var d = Math.random();

    if (d < 0.90) {
      str = "Avaliable";
      text = str.fontcolor("green");
      x = true;
    } else {
      str = "Not Available";
      text = str.fontcolor("red");
      y = false;
    }

    elem.innerHTML = text;
  }
}
<p id="demo1" class="demo"></p>
<p id="demo2" class="demo"></p>
<p id="demo3" class="demo"></p>

Answer №3

Your loop is prematurely ending due to the "break" statement, only iterating over the first element.

To ensure each element updates independently, create a text generation function and call it on each element individually as shown below:

var myVar = setInterval(updateText, 1000);

function updateText(){
    var elements = document.querySelectorAll('.element');
  Array.from(elements).forEach(item => {
    item.innerHTML = generateText();
  })
}

function generateText(){
    var randNum = Math.random();
  if (randNum > .9) {
    return "Open";
  } else {
    return "Closed"
  }
}

Check out this JSFiddle link for the working code: https://jsfiddle.net/4whxv5q3/. Feel free to customize the text color or any other modifications you desire.

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

The EXIF-JS data is becoming inaccessible beyond the method's scope

Currently, I am in the process of developing a web application using Angular 8. My main objective is to access the exif data of an input image outside the getData method by assigning the obtained data to a global variable. However, when attempting to acces ...

Retrieve the most recent information from a web scraper and display it on the Heroku application

After creating an API with Express.js and using cheeriojs to scrape a website, I deployed the API on Heroku. However, my web application is not fetching the latest data from the scraped website. It seems to be stuck showing old data. How can I make it co ...

Encountered a server error while trying to export from Content

I'm attempting to retrieve data from a specific space in Contentful by utilizing the https://github.com/contentful/contentful-export npm package. However, when I execute my code following the example provided on the GitHub page, I encounter the follow ...

What is the process for accessing a particular field in the data returned by the collection.find method in Expressjs and mongodb

I've been attempting to access a specific field returned from the mongodb collection.find method without success. The console.log is not displaying anything. router.get('/buildings', function(req, res, next) { var db = req.db; var collectio ...

React: Issue with For Loop not recognizing updates in Hook's State

Recently, I successfully created a React application that displays each word of a sentence at a user-defined time interval for fast reading. However, I am now facing a challenge as I attempt to add a pause button functionality to the app. When I press the ...

Choose a single asset from the list of values stored in the Map

I'm looking to implement something similar to the following: let myMap = new Map<string, any>(); myMap.set("aaa", {a: 1, b: 2, c:3}); myMap.set("bbb", {a: 1, b: 2, c:6}); myMap.set("ccc", {a: 1, b: 2, c:9}); let cs = myMap.values().map(x => ...

Ensuring the accurate usage of key-value pairs in a returned object through type-checking

After generating a type definition for possible response bodies, I am looking to create a function that returns objects shaped as { code, body }, which are validated against the typing provided. My current solution looks like this: type Codes<Bodies> ...

Utilizing @Material-UI Tabs for a Stylish Navigation Bar

As a newcomer to the coding realm, I find myself on a quest for an answer that has proven elusive. Despite scouring various sources, none of the solutions I've stumbled upon seem to work in my case. The issue at hand revolves around my desire to util ...

Generate a distinct identifier for the select element ID whenever a new row of data is inserted into a table

Although my title accurately describes my issue, I believe the solutions I have been attempting may not be on the right track. I am relatively new to javascript and web development in general, so please forgive me for any lack of technical terminology. Th ...

Ways to dynamically apply styles to the component tag depending on the visibility of its content

Consider a scenario where you have a component with logic to toggle the visibility of its contents: @Component({ selector: 'hello', template: `<div *ngIf="visible"> <h1>Hello {{name}}!</h1></div>`, styles: [`h1 { fo ...

How to retrieve JSON data in Angular.js

I'm having trouble accessing a json file in angular.js with the code below. I keep getting an error message and could really use some help! Here is my module : angular.module("demoApp", ['demoApp.factory','demoApp.controllers']); ...

What will occur if I use an XMLHttpRequest to request a file that is currently being downloaded?

My goal is to enhance links in a progressive manner using the PJAX style. My plan was to layer this on top of some regular prefetch <link>s: <link rel="prefetch" href="next.html"/> If the browser has already downloaded next.html, then the PJA ...

Using JavaScript to automate keystrokes programmatically

Is there a way to programmatically close a webpage using the keyboard shortcut control + W? I'm wondering if I can write code that will mimic this specific shortcut (control+W). ...

Querying the api for data using Angular when paginating the table

Currently, I have a table that retrieves data from an API URL, and the data is paginated by default on the server. My goal is to fetch new data when clicking on pages 2, 3, etc., returning the corresponding page's data from the server. I am using an ...

What could be causing the delay in $q.all(promises).then() not waiting for the promises to complete?

Currently, I am tasked with utilizing AngularJS 1.5.5. My task involves making calls to multiple Rest-Services and handling the results simultaneously. $scope.callWebservices = function(){ let promises = { first: callFirstWebservice(), ...

Creating dynamic styles with Material-UI's useStyles

Attempting to implement the same logic using material-ui's useStyle feature <div className={'container ' + (state.unlocked ? 'containerUnlocked' : '')}> I thought it might look like this: <div className={`${clas ...

The JQuery ajax post function is typically called towards the conclusion of a JavaScript script

I am struggling with validating whether a username is already taken. I have been attempting to determine if the username exists by utilizing the "post" method in jQuery. However, every time I execute this function, the script seems to skip to the end of th ...

Is there a bug in Safari 8.0 related to jQuery and backslashes?

I am using Mac OS 10.10 Yosemite and Safari 8.0. Attempting to read an XML (RSS) file: <content:encoded>bla bla bla</content:encoded> The Javascript Ajax method I am using is: description:$(valeur).find('content\\:encoded&apo ...

Leveraging Ajax for Executing a MySQL Query in PHP upon Clicking the Facebook Like Button

Is it possible to execute a MySQL query whenever a Facebook Like button is clicked on a webpage? I am aware that FB.Event.subscribe('edge.create', function(response) {} is used for such actions. However, my lack of knowledge in Javascript and AJA ...

Efficiently sending a cookie with an Axios POST Request

My request is not receiving a cookie even after trying various solutions like withCredentials. I have pasted the most recent code here, can anyone spot what might be missing? var cookie_for_data = "token=test"; var host = "http://localh ...