By Checked rs


2019-04-15 10:21:50 8 Comments

I'm struggling on write my code. What I am trying to do:

  • Insert random numbers every few sec next to the "show" elements, when its say its available.

Expected Result

  • When its "Not available", no numbers can be inserted in.
  • When its "Available", numbers can be inserted in.

var myVar = setInterval(breakdown, 2000);
/*

var myVar1 = setInterval(random, 1000);

function random() {
  var n = Math.floor((Math.random() * 10) + 1);
  let loops = Array.from(document.querySelectorAll('.show'));
  for (const loop of loops) {
    if () {
      loop.innerHTML = n;

    }
  }
} 

*/

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 id="show1" class="show"></p>
  <p id="demo2" class="demo">
    <p id="show2" class="show"></p>
    <p id="demo3" class="demo">
      <p id="show3" class="show"></p>

1 comments

@Aaron Tee 2019-04-15 10:45:55

In order to read other elements' (such as sibling in this case) state ('Available' or 'Not Available') for switching work, you can call the previousSibling of the target property then access its innerHTML. Read more about previousSibling dom property. https://www.w3schools.com/jsref/prop_node_previoussibling.asp

fiddle

Related Questions

Sponsored Content

79 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5781382 View
  • 7209 Score
  • 79 Answer
  • Tags:   javascript arrays

35 Answered Questions

[SOLVED] How do I return the response from an asynchronous call?

54 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

38 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

55 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

3 Answered Questions

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

14 Answered Questions

[SOLVED] How to insert an item into an array at a specific index (JavaScript)?

76 Answered Questions

[SOLVED] How do I detect a click outside an element?

  • 2008-09-30 13:17:12
  • Sergio del Amo
  • 1101402 View
  • 2263 Score
  • 76 Answer
  • Tags:   javascript jquery

Sponsored Content