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

Unable to transmit Javascript array to PHP using Ajax

I've been pulling my hair out over a seemingly simple problem. Here is the JavaScript array that's causing me trouble: var orderDetailsArray = new Array(); orderDetailsArray[0] = 'test 1'; orderDetailsArray[1] = 'test ...

I am confused about the process of mounting components

Utilizing pattern container/representational components, I have a CardContainer component that retrieves data from a server and passes it to a Card component. Container Component: class CardContainer extends Component { state = { 'ca ...

Automatically unselect the "initially selected item" once two items have been selected in Material UI

As someone new to web development, I'm struggling with a specific task. Here is the issue at hand: I have three checkboxes. If box1 and then box2 are selected, they should be marked. However, if box3 is then selected, box1 should automatically unchec ...

After placing two divs within another div and applying justify content, an unexpected blank space has appeared

I am currently working on a website project using the Next.js framework for React and Tailwind CSS for styling. However, I have come across an issue that is causing some trouble. My goal is to position an image on the right side of the page while keeping t ...

Does the Angular templateCache get shared across different applications? And does it stay persistent?

Is it possible for two Angular applications that operate on the same domain to exchange data within the templateCache? Or does each main application module have its own unique cache? I am curious about the circumstances under which a new templateCache is g ...

When the width of the window is hidden, conceal

My webpage has a carousel with pictures, but on smaller devices, they do not appear properly. I am now trying to figure out how to hide the div if the width is less than 1015px. Here is the code for my div: <html> <body> <div id="myCarou ...

AngularJS - Sending configuration values to a directive

I'm trying to figure out how to pass parameters (values and functions) to an Angular directive. It seems like there should be a way to do this in Angular, but I haven't been able to locate the necessary information. Perhaps I'm not using th ...

Setting properties on functions and defining their prototype

My task involves working on the following block of code: function Vector(x, y) { this.x = x || 0; this.y = y || 0; } Vector.add = function(a, b) { return new Vector(a.x + b.x, a.y + b.y); }; Vector.sub = function(a, b) { return new Vecto ...

I am attempting to utilize the fetch API method to initialize the store's state, but for some reason, it is not functioning properly

Within my store.js file, I have a state called user_data, with its initial method set to fetch_user_data: export default new Vuex.Store({ state: { user_data: util.fetch_user_data('username') ... } located in the util.js file: util. ...

Grid layout with card tiles similar to Google Plus

I'm looking to develop a scrolling grid with card tiles similar to Google Plus that has three columns. I am currently using Material UI, but I can't seem to find the right functionality for this. I have experimented with the standard Material UI ...

My goal is to retrieve and print the duplicated values only once from an associative array

Given an associative array, I need to print all the department names without any repetitions. <h3>2. List out all department names</h3> <div class="all"> </div> Here is my JavaScript code: var employee=[{"firstName":"Zahir","last ...

Using JavaScript for Text Processing on Disk

Currently, I have a set of HTML files that require automated processing such as regex replacements and more complex actions like copying specific text blocks from one file to another. I am considering creating a series of scripts to handle this processing ...

I'm looking for the specific jQuery/JavaScript function that will accomplish this task

let data = [{ name: "abcd", type: "1 kg" }, { name: "efgh", type: "1 cai" }, { name: "ijkl", type: "1 kg" }]; If I have the name, I would like to get the corresponding type. For example, if I call getType('abcd'), it sho ...

Is it possible to dynamically change the color of text based on its position using CSS, JS, or JQuery?

I am currently working on a corporate website and have been tasked with creating a unique design for a specific page. The design includes the following elements: A body background gradient that transitions from their primary color to white in a top-to-bot ...

Adding key/value pairs to an array of objects in RxJS Observables can be easily

I currently have an Angular app with state management that retrieves data from a database in observables. Here is an example of the interfaces I am working with: interface Service { id: number, name: string, category_id: number, } interface Category ...

Solving the issue of image paths within external SCSS files in Nuxt.js

Trying to organize my component scss files separately from their Vue components has been a bit challenging. I also have a GLOBAL scss file that is not scoped, but no matter which approach I take, I can't seem to get the image paths in /assets or /stat ...

What is the best way to conceal certain choices in a dropdown menu?

How can I display only the cities in Australia in a dropdown list? I have tried to find "Australia" in the options and hide everything before and after it, but I have been unsuccessful! Here is my fiddle. <select class="dropdown" id="dropdown"> ...

I’m keen on utilizing JQuery with Node.js and EJS, but I’m encountering an issue where $ is not

I attempted to incorporate JQuery in my project by following these steps. Installed jquery using npm install Modified the package.json file Despite this, the functionality still does not work as intended. Below is a snippet of the .ejs page: <html& ...

Modify the input based on the chosen option operation

I am working on a project where I have 3 select elements and when a user selects an option, the associated value should be displayed in an input field. I am trying to use a single function for these 3 selects, but I am facing some issues. Here is the HTML ...

Using Jquery and AJAX to dynamically fill out an HTML form based on dropdown selection

My goal is to populate a form on my webpage with information pulled from a MySQL database using the ID of the drop-down option as the criteria in the SQL statement. The approach I have considered involves storing this information in $_SESSION['formBoo ...