does indexOf() in js searches all the elements of an array to execute?

const arr = ['a','b','c']; 
for (let char of arr) {
  console.log(char);
}

I believe that time complexity of code above is O(n).

const arr = ['a','b','c']; 
for (let char of arr) {
  console.log(arr.indexOf(char);
}

However, does indexOf() search all the elements?
If does so, I believe time complexity of code above may be O(n^2)

I want to know whether indexOf() searches all the components as for loop.

how to allign word break on both sides of print page? – media query

I’ve kept a Javascript function printthis() for printing purpose that prints everything in the div id printthis except what is given with the class d-print-none. The code works good in the opening page, the page before printing. But Upon clicking print, the word-break given for the div class address2 & ml-auto address are not working.The word-break will work fine if the address value comes in the div ml-auto address is a small string. i wanted the word-break to work good for the address block like it appears in the page before printing. How can i fix this?Can i get some help?

i tried assigning a width like for the address block ,ie, div ml-auto address.But it is also not working.

https://jsfiddle.net/1peoqsgc/2/

The full script & css is availble in the above link.

<div id="printthis">
        <div class="container-fluid">
            <div id="ui-view" data-select2-id="ui-view">
                
                    <div class="card">
                        <style>
                          @media print {
                             .address {
                                    float: right;
                                    word-wrap: break-word;
                                }

                                .address2 {
                                    float: left;
                                    word-wrap: break-word;
                                }
                        }
                   </style>
             <div class="card-body">
                            <div class="row mb-4">
                                <div class="col-sm-4 address2">
                                  <div style="width: 405px;"> abcdfjsdfjfd firi,iiii, 29978876, dfdgfdgdhfghfghiiiiiiiiiiiiiiiiiii</div>

                                </div>
                                <div class="col-sm-4 ml-auto address">
                                   <div>kkkkkkk i u ppppp 112233444, mkmmkkkl, 5675675675, lkljh po</div>
                               </div>
                           </div>

HTML Script RegEx

I have an HTML script that’s being tested against the following regular expression, and I dont get how to translate it:
((.+<“br” /> (n){3}.+n.+*)

The regex has the br without the quotations that I added, but without the quotations StackOverflow wouldn’t format the regex properly

eventListener is not running

I am making an extension in which a user can make notes by taking screenshots and then download his notes in pdf format.
In this extension I made my custom context menu and it will only be visible when the user right clicks on the image tag, else the default context menu will appear.
In this extension I made an text editor, and used execcommand() method to bold, italic, undeline the text, or to generate link, insert unordered list etc.

Problem :- So, my problem is when the user right clicks on the image it shows my custom context menu, but when I center, align right or justify this image in my text editor and then right click on it, it do not show my custom context menu, it shows default context menu. Why is this happening, can anyone help me.

function showContextMenu(e){
    e.preventDefault();
    
        const {clientX: mouseX, clientY: mouseY} = e;
    
        const {normalizedX, normalizedY} = normalizePosition(mouseX, mouseY);
    
        contextMenu.style.top = `${normalizedY}px`;
        contextMenu.style.left = `${normalizedX}px`;
    
        contextMenu.classList.remove("visible");
    
        setTimeout(() => {
            contextMenu.classList.add("visible");
        });
}

// Hide the custom context menu when left or right clicked outside the contexet menu
scope.addEventListener("click", (e) => {
    if(e.target.offsetParent != contextMenu) {
        contextMenu.classList.remove("visible");
    }
});
scope.addEventListener("contextmenu", (e) => {
    if(e.target.offsetParent != contextMenu) {
        contextMenu.classList.remove("visible");
    }
});

//Function for the context menu's option;
function executingOptions(e) {
    for(let i = 0; i < options.length; i++){
        if(options[i].innerHTML == "Crop"){
            options[i].onclick = () => {
                /////////////////////////////////////////////////////////////////
                contextMenu.classList.remove("visible")
            }
            continue;
        }
        if(options[i].innerHTML == "Download"){
            options[i].onclick = () => {
                console.log(e.target.src);
                options[i].setAttribute("href", e.target.src);
                contextMenu.classList.remove("visible")
            }
            continue;
        }
        
        options[i].onclick = () => {
            e.target.setAttribute("width", options[i].innerHTML);
            contextMenu.classList.remove("visible")
        }
    }
}

//This code is adding event listener to every image in the text editor {this is only part of big function not entire code}
    newImage.addEventListener("contextmenu", () => {
        showContextMenu(event);
        executingOptions(event);
    });

//This code will center the content in text editor {part of the code not entire code}
button.onclick = () => {
        document.execCommand("justifyCenter");
        textEditor.focus();
}

JavaScript Button input and output reset

I’m working with a button and a text label in javascript and HTML. I have a code that clears the input text label, but i also need the same button to clear the output message it gives = “helloNameOP”. How would I add the 2 in the same function? I have both my codes listed below, that work perfectly separated, but I cant figure out how to put them together to work simultaneously.

What I have tried:

 //for removing the Input text label:
onclick = document.getElementById("helloNameInput").value="";


//for removing the Output message recieved:
inputField = document.getElementById("helloNameOP")
document.getElementById('helloNameOP').textContent = " "

I’m not a javascript person, more of a kotlin gal, so I’m trying to learn.

SyntaxError: Unexpected token ‘;’ while compiling ejs while trying to make data to a table html

Detailed Error Image

<body>
<h1>Hello, world!</h1>
<table class="table">
  <thead>
    <tr>
      <th scope="col">Command</th>
      <th scope="col">Total</th>
      <th scope="col">Success</th>
      <th scope="col">Last</th>
    </tr>
  </thead>
  <tbody>
  <%Object.entries(global.db.data.stats).map(([name, data]) => ({%>
    <tr>
      <th scope="row"><%= name =%></th>
      <td><%= data.last =%></td>
      <td><%= data.total =%></td>
      <td><%= data.success =%></td>
    </tr>
  <%})%>
  </tbody>
</table>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

i am very new to ejs and still learning, i am trying to make global.db.data.stats to become a table

Why is Net.Socket.Write() not sending the full string to my TCP client?

Everything else works fine. The server is well aware of the usernames associated with the clients and it sends information to them accordingly, but the weird thing is the string cuts off after the first variable. Here is the loop for a typical send message:

function SendMessage(msg, client)
{

    const clientName = ClientNames.get(client);
    let recieverMsg = `${clientName}: ${msg}`;

    console.log(recieverMsg);


    Clients.forEach(elm => {
        if(elm != client)
        {
            elm.write(recieverMsg);
        }
        else {
            elm.write("You: " + msg);
        }
    })

}

msg is the chunk.toString() in the socket.on(‘data’) event, again, node picks up what this string means, it debugs fine but in the client (imagine the windows cmd) itll just print the username and go to the next line.

The loop for the client side is pretty simple too,

char buff[4090];

do
    {
        ZeroMemory(buff, 4090);
        int messageRevieved = recv(sock, buff, 4090, 0);

        if (messageRevieved > 0)
        {
            userInput->FreezeInput();
            cout << buff << endl;
            userInput->UnFreezeInput();
        }

    } while (0 == 0);

User input is handled in its own class on a seperate thread, again, working just fine.

I think it has to do with a misunderstanding of what socket.write and recv actually do or maybe I just dont understand javascript strings enough. Either way this problem is annoying because its the last step in creating my app

Ive done some extensive tests too, it really just doesnt like the concat strings. Itll print everything up until the first variable, meaning I could have socket.write(“hehehehehehe ” + variable1 + ” kadjgkdgad”); and it would print hehehehehe [variable1 value] and just stop

Tl;dr: The server will write to the sockets up to the first variable in a concat’d string and then stop, its so weird.

EDIT: The dependencies used serverside are Net and dotnet if that makes a difference.

Dynamically displaying data results from left to right in table columns from json array

I wanted to achieve similar result as shown in below image.

Expected result:

Question: Looking for Jquery or javascript solution to dynamically displaying data results from left to right in table columns from json array.

Your help is much appreciated.

Here is my HTML & JSON format and what I am trying to achieve:

<table>
<tr>
    <td rowspan='2'>ID</td>
    <td rowspan='2'>Bagian</td>
    <td colspan='12'>Tahun</td>
</tr>
<tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
    <td>5</td>
    <td>6</td>
    <td>7</td>
    <td>8</td>
    <td>9</td>
    <td>10</td>
    <td>11</td>
    <td>12</td>
</tr>
<tbody id="zone_data">
</tbody>

const data = 
  { result: 
    [ { TPM_MESIN_ID: 'CPU-20220115112327418526-20220122140952287412'
      , KOMPONEN: 
        [ { TPM_MESIN_KOMPONEN_ID   : '20220115112327418531-20220122140952462116'
          , TPM_MESIN_KOMPONEN_NAMA : 'CPU01'
          , BERKALA: 
            [ { TPM_BERKALA_ID: '20220127142100262686', TPM_BERKALA_JADWAL_MINGGU: 'M-1',  TPM_BERKALA_JADWAL_BULAN: '1', TPM_BERKALA_PERIODE: '1' } 
            , { TPM_BERKALA_ID: '20220127154027581689', TPM_BERKALA_JADWAL_MINGGU: 'M-13', TPM_BERKALA_JADWAL_BULAN: '6', TPM_BERKALA_PERIODE: '2' } 
            , { TPM_BERKALA_ID: '20220129084334483646', TPM_BERKALA_JADWAL_MINGGU: 'M-28', TPM_BERKALA_JADWAL_BULAN: '9', TPM_BERKALA_PERIODE: '3' } 
          ] } 
        , { TPM_MESIN_KOMPONEN_ID   : '20220115112327418532-20220122140952272413'
          , TPM_MESIN_KOMPONEN_NAMA : 'MNT01'
          , BERKALA: 
            [ { TPM_BERKALA_ID: '20220127142100262698', TPM_BERKALA_JADWAL_MINGGU: 'M-2',  TPM_BERKALA_JADWAL_BULAN: '1',  TPM_BERKALA_PERIODE: '1' } 
            , { TPM_BERKALA_ID: '20220127142100262699', TPM_BERKALA_JADWAL_MINGGU: 'M-12', TPM_BERKALA_JADWAL_BULAN: '5',  TPM_BERKALA_PERIODE: '2' } 
            , { TPM_BERKALA_ID: '20220127142100262700', TPM_BERKALA_JADWAL_MINGGU: 'M-31', TPM_BERKALA_JADWAL_BULAN: '10', TPM_BERKALA_PERIODE: '3' } 
          ] } 
        , { TPM_MESIN_KOMPONEN_ID   : '20220115112327418533-20220122140952428562'
          , TPM_MESIN_KOMPONEN_NAMA : 'KYB01'
          , BERKALA: [] 
      } ] } 
    , { TPM_MESIN_ID: 'CPU-20220115112327418526-20220122140952287555'
      , KOMPONEN: 
        [ { TPM_MESIN_KOMPONEN_ID   : '20220115112327418531-20220122140952462117'
          , TPM_MESIN_KOMPONEN_NAMA : 'CPU02'
          , BERKALA: 
            [ { TPM_BERKALA_ID: '20220127142100262686', TPM_BERKALA_JADWAL_MINGGU: 'M-5', TPM_BERKALA_JADWAL_BULAN: '2', TPM_BERKALA_PERIODE: '1' } ] 
  } ] } ] } 

function createRowHTML()
  { 
  var tableContent = "";
  for (var j = 0; j < data.result.length; j++) 
    {
                        
    }               
  $("tbody#zone_data").html(tableContent);
  }
    
$(function(){createRowHTML();});

How can i stop the iteration of a Generator?

My following function is a Generator function* generator(arr) { now i want to pass from js to ruby, i want to stop the iteration to do that in js i stopped with .done, in ruby how can i stop?

in javascript i used to use .done to stop the iteration of an Generator

like this:

function* generator(arr) {
}

function definition(){
const state = data.map(v => iterHeapsAlgo(v));
while(true) {
    const isEnd = state.every((v,i) => {
      let n = v.next();
      if(n.done) {

now i am becomming my code from js to ruby

how can i stop the iteration if(n.done) { in ruby?

React not re-rendering after state update

I’m currently learning React. In my homepage component, I’m using a hook to initialize and populate the state. I have 2 states, 1 contains a random pokemon and another is an array of 20 random pokemons. The first one works fine, but not the array.

Here’s the homepage component:

// Hook
import { useHomeFetch } from "../hooks/useHomeFetch";
// Image
import NoImage from '../images/missingno.png';

const Home = () => {
    const { state, collection, loading, error } = useHomeFetch();
    return (
        <>
            { state.heroPokemon ?
            <HeroImage 
                image={`${API.fetchSprite(state.heroPokemon)}`}
                title={state.heroPokemon.name}
                text='Placeholder, should include abilities, etc. to show the pokemon off.'
            />
            : null}
            { collection.pokemons[0] ?
            <Grid header='Popular pokemons'>
                {collection.pokemons.map( pokemon => (
                    <h3 key={pokemon.id}>{pokemon.name}</h3>
                ) )}
            </Grid>
            : null}
        </>
    );
}

export default Home;

The heroPokemon works fine after I added the conditional rendering. My first thought was to do the same thing with the collection, as it might have rendered before all of the API call promises have resolved.

If I look at the react dev tools, this is what I see for the state:

hooks
HomeFetch

1 State : {heroPokemon: {…}}
2 State : {pokemons: Array(20)}
           pokemons :
               [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, …]

So it looks to me that the call indeed completed fine with 20 random pokemon objects in there.

Here’s is the hook:

const initialState = {
    heroPokemon: null
}

const fetchRandomPokemons = async (ids) => {
    let pokemons = [];
    ids.forEach(async num => {
        pokemons.push(await API.fetchPokemon(num));
    });
    return pokemons;
}

export const useHomeFetch = () => {
    const [state, setState] = useState(initialState);
    const [collection, setCollection] = useState({pokemons: []});
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(false);
    
    const fetchPokemons = async (limit = 20) => {
        try {
            setError(false);
            setLoading(true);
            
            const heroPokemon = await API.fetchPokemon(randomInt(1, 898));
            const randomInts = randomUniqueInt(1, 898, limit);
            const pokemons = await fetchRandomPokemons(randomInts);

            setState(prev => ({heroPokemon}));
            setCollection(prev => ({pokemons}));
        } catch (error) {
            setError(true);
        }
        setLoading(false);
        
    };
    // Initial render
    useEffect(() => {
        fetchPokemons(20);
    }, [])

    return { state, collection, loading, error };
};

When I take out the conditional, Grid shows up, but it doesn’t have the h3s with the pokemon names in them. If I console.log out state and collection right before the return in home. The last few ones show the correct state.heroPokemon and collection.pokemons populated correctly. This leads me to believe that the states are updated correctly, but why is React not re-rendering the grid component?

To add, I also tried adding this:

<p>{collection.pokemons[0]}</p>

To the home component, and nothing shows up. I feel like I may be misunderstanding or missing a crucial part of how states and re-renders work, which is leading me to missing what I could be doing wrong.

CSS Animation Issue – Button Animation

I have the following code:

var basicTimeline = anime.timeline({
  autoplay: false,
});

var pathEls = $(".check");
for (var i = 0; i < pathEls.length; i++) {
  var pathEl = pathEls[i];
  var offset = anime.setDashoffset(pathEl);
  pathEl.setAttribute("stroke-dashoffset", offset);
}

basicTimeline
  .add({
    targets: ".text",
    duration: 1,
    opacity: "0"
  })
  .add({
    targets: ".button",
    duration: 1300,
    height: 20,
    width: 81,
    backgroundColor: "#717F7E",
    border: "0",
    zIndex: 0,
    borderRadius: 100
  })
  .add({
    targets: ".progress-bar",
    duration: 2000,
    width: 81,
    easing: "linear"
  })
  .add({
    targets: ".button",
    width: 0,
    duration: 1
  })
  .add({
    targets: ".progress-bar",
    width: 40,
    height: 39,
    delay: 500,
    duration: 750,
    borderRadius: 80,
    backgroundColor: "#71DFBE",
    left: 20
  })
  .add({
    targets: pathEl,
    strokeDashoffset: [offset, 0],
    duration: 200,
    easing: "easeInOutSine"
  });


$(".button").click(playButtonAnim);

$(".text").click(playButtonAnim);

function playButtonAnim() {
  basicTimeline.play();
}

//error animation
const form = document.forms.myform;
form.onsubmit = e => {
  e.preventDefault()
  let data = Object.fromEntries(new FormData(form).entries())

  console.log(data)

  let validationOK = true
  for (let entrie in data) {
    if (!form[entrie].checkValidity()) {
      validationOK = false
      form[entrie].classList.add('shakingErr')
      setTimeout(() => {
        form[entrie].classList.remove('shakingErr')
      }, 820)
    }
  }
  if (validationOK) {
    fetch(form.action, {
        method: form.method,
        body: JSON.stringify(data),
        headers: {
          Accept: 'application/json'
        }
      })
      .finally(() => {
        window.location = "thankyou.html"
      })
  }
}
/* Contact Form */

input[type=text],
[type=email],
select,
textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #555;
  margin-top: 6px;
  margin-bottom: 16px;
  resize: vertical;
}

input[type="text"]:focus,
input[type="email"]:focus,
#subject:focus {
  background: var(--bgFormElsFocus);
  transform: scale(1.02);
  transition: transform 0.2s ease-in-out;
}

.contactform {
  position: relative;
  border-radius: 50px;
  background-color: #f2f2f2;
  padding: 5px;
  z-index: 2;
  display: block;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: auto;
  margin-top: 1%;
  width: 100%;
  animation-name: gradient;
  animation-duration: 3s;
  animation-iteration-count: infinite;
}

.contactform:hover {
  animation-name: gradient;
  animation-duration: 15s;
  animation-iteration-count: infinite;
}

.column {
  float: center;
  width: 50%;
  margin-top: 6px;
  padding: 20px;
  display: block;
  margin-left: auto;
  margin-right: auto;
}

.row:after {
  content: "";
  display: table;
  clear: both;
}

@media screen and (max-width: 600px) {
  .column,
  input[type=submit] {
    width: auto;
    margin-top: 0;
  }
}

.shakingErr {
  border-color: red;
  animation: shake 0.82s forwards;
}

@keyframes shake {
  10%,
  90% {
    transform: translate3d(-1px, 0, 0);
  }
  20%,
  80% {
    transform: translate3d(2px, 0, 0);
  }
  30%,
  50%,
  70% {
    transform: translate3d(-4px, 0, 0);
  }
  40%,
  60% {
    transform: translate3d(4px, 0, 0);
  }
}


/* fancy button styles */

.buttonWrapper {
  height: 39px;
  width: 81px;
  position: relative;
}

.button {
  background: #2B2D2F;
  height: 39px;
  width: 81px;
  text-align: center;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  left: 0;
  cursor: pointer;
  border-radius: 4px;
  z-index: 10;
}

.text {
  font: .8rem/1 poppins;
  color: #71DFBE;
  position: absolute;
  top: 50%;
  transform: translateY(-52%);
  left: 0;
  right: 0;
  cursor: pointer;
}

.progress-bar {
  position: absolute;
  height: 20px;
  width: 0;
  left: 40px;
  top: 50%;
  border-radius: 200px;
  transform: translateY(-50%) translateX(-50%);
  background: black;
}

svg {
  width: 15px;
  position: absolute;
  top: 50%;
  left: 20px;
  transform: translateY(-50%) translateX(-8px);
}

.check {
  fill: none;
  stroke: #FFFFFF;
  stroke-width: 3;
  stroke-linecap: round;
  stroke-linejoin: round;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>replit</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
  <link href="https://fonts.googleapis.com/css?family=Poppins:600" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Poppins:600" rel="stylesheet">
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.js">
  </script>

</head>

<body>
  <!-- start contact section -->
  <section id="contact">
    <div class="container" data-aos="fade-up">
      <div class="contactform">
        <div style="text-align:center">
          <div class="section-title">
            <h2><br />Get In Touch</h2>
          </div>
          <p>Feel Free To Reach Out To Me Through This Form! </p>
        </div>
        <div class="row">
          <div class="column">
            <form name="myform" action="https://formspree.io/f/xrg123232jbqpq" id="my-form" method="POST" novalidate>
              <label for="firstname">First Name</label>
              <input type="text" id="first name" name="firstname" placeholder="Your First Name.." required>
              <label for="lastname">Last Name</label>
              <input type="text" id="lastname" name="lastname" placeholder="Your Last Name.." required>
              <label for="email">Email:</label>
              <input type="email" id="email" name="email" placeholder="Your Email.." required>
              <label for="subject">Subject</label>
              <textarea id="subject" name="subject" placeholder="Lets Collaborate.." style="height:170px" required></textarea>
              <!-- <input type="submit" value="Submit"> -->
              <div class='buttonWrapper'>
                <div class="button">
                  <div class="text">Submit</div>
                </div>
                <div class="progress-bar"></div>
                <svg x="0px" y="0px" viewBox="0 0 25 30" style="enable-background:new 0 0 25 30;">
                  <path class="check" class="st0" d="M2,19.2C5.9,23.6,9.4,28,9.4,28L23,2" />
                </svg>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </section>
  <script src="script.js"></script>
</body>

</html>

The only problem I’m facing is that even though I have error animation code in the JS that calls in the shakingErr class from CSS, the animation seems to be not working when the user clicks submit with empty/wrong fields. How can I make it so that when the user clicks the submit button, the contact form has a shaking error button.

Notice that when you click the submit button, there is also an animation that plays on the button? I would not like that animation to play when the user clicks submit button on empty fields. I would only like the animation to play once the user has filled all the information in the input fields.

Any suggestions?

EXPECTED OUTPUT

https://watch.screencastify.com/v/D2VXp3493XZXl3Lmh7yR

As you can see, whenever the user tries to click submit button on empty/wrong fields (Email) then the error animation plays. Also, the button animation should not play when the user clicks the submit button on empty/wrong fields. It should play once the fields are filled and are right.

Any suggestions?

Changing a HTML element at a certain time and date

I have an open and closed indicator (Thanks to those who helped me!) that shows I am open from 8:00 AM to 10:00 PM and from 10:00 PM to 8:00 AM I am closed, but it shows this even on a weekend when I am not open. Can you help me make the Javascript say I am closed when it is a weekend and on a holiday like December 24-25? Below will be my current code. Thanks!

Javascript:

var messageElement = document.getElementById("message");
var circleElement = document.getElementById("circle");

const refreshStatus = () => {
  // Set the current time
  let currentDate = new Date().getHours();
  // If the time is between 8 am and 10 pm
  if (currentDate >= 8 && currentDate <= 21) {
    // Update text and add classes
    messageElement.innerHTML = "We are open until 10 PM";
    circleElement.className = 'open-circle';
    messageElement.className = 'open-p';
  } else {
    // 21 pm to 8 am
    messageElement.innerHTML = "We are closed until 8 AM";
    circleElement.className = 'closed-circle';
    messageElement.className = 'closed-p';
  }
}

// run when starting
refreshStatus();

// updates every 8 seconds
setInterval(refreshStatus, 8000);

CSS:

/* Start indicator CSS */

.open-circle {
  position: relative;
  top: 23rem;
  height: 1.5625rem;
  width: 1.5625rem;
  background-color: #00BF13;
  border-radius: 50%;
  display: inline-block;
}

.open-p {
  position: relative;
  top: 23rem;
  color: #00BF13;
  font-weight: bold;
  display: inline-block;
  width: 8rem;
}

.closed-circle {
  position: relative;
  top: 23rem;
  height: 1.5625rem;
  width: 1.5625rem;
  background-color: #ea001d;
  border-radius: 50%;
  display: inline-block;
}

.closed-p {
  position: relative;
  top: 23rem;
  color: #ea001d;
  font-weight: bold;
  display: inline-block;
  width: 8rem;
}

/* End indicator CSS */

HTML:

<!-- Start status indicator -->

<div id="circle"></div>
<p id="message">We are open until 10 PM</p>
<script src="js/open-closed-indicator.js"></script>

<!-- End status indicator -->

Creating a div and inserting HTML

I’m trying to create this in Javascript so that I can insert it into the document:

    <div class="listing-small-badge award-badge" style=" vertical-align: top; position: relative; top: -250px; z-index: 2;"><i class="fa fa-tag award" style="background-color: #990000;"></i>Highest Rated</div>

And I’ve tried everything I can think of, but once I create the ‘i’ element, I can’t seem to properly append it to the div element.

For example:

    <script type="text/javascript">
    var div = document.createElement("div");
    div.style.cssText += 'vertical-align:top; position: relative; top:-250px; z-index:2;';
    div.classList.add("listing-small-badge");
    div.classList.add("award-badge");
    div.innerHTML = "Highest Rated"; //this works on its own, but disappears if/when I try to append the 'i' element/HTML tag
    var i = document.createElement("i");
    i.classList.add("fa");
    i.classList.add("fa-tag");
    i.classList.add("award");
    //i.style.cssText("background-color: #990000;"); //doesn't like this for some reason TBD
    //console.log(i); //prints out just fine
    //div.innerHTML += i; //results in an empty div
    //div.innerHTML += '<i class="test">x</i>'; //results in an empty div
    //div.insertAdjacentHTML("afterend", "<i class='test'></i>"); //results in "The element has no parent."
    console.log(div);
    </script>