I would like to know how I can make the “namePrinter” loop function work well?

I was trying to get javascript to print the result of the “generateName” function at least 10 times when I press a button in the html, so i tried a loop inside the function that generates the names and but it didn’t work then I separated the loop and wrote it in the function “namePrinter” and create the global variable “names” to store the results of the function “generateName”
but I don’t know what part of this whole process is wrong, I already reviewed other questions that were made in this forum but I didn’t find an answer either

JS:

//this run the funtion that prints the names
document.getElementById("elvenFemButton").onclick = namePrinter;

//cutting characters function
function capFirst(string){
    return string.charAt(10).toUpperCase() + string.slice(1);
}

//Randomizer
function getRandomInt (min,max){
    return Math.floor(Math.random() * (max-min)) + min;
}

//this function generates names using both "elfFemName" and "elfLastName" and the functions from above
function generateName(){
    var elfFemName1 = ["Adaia","Alisaie","Allisara","Alengwan","Alglaranna","Alachia","Alysia","Amberle","Anethra","Anwen","Apolline","Arathel","Ariane","Arianni","Ariel","Arwen","Ashalle","Ashniel","Atara","Ayara","Brelyna","Briala","Celebrían","Clothild","Cullich","Cylia","Dalish","Dirael","Eldyra","Elanor","Elenwen","Elezen","Ellia","Elynea","Éowyn","Failla","Faralda","Fleur","Freyalise","Galadriel","Gheyna","Jenassa","Katriel","Kira","Laina","Laniatte","Lauriel","Liallan","Liriel","Liselle","Loriel","Lorian","Lúthien","Máire","Mayael","Merril","Miara","Mihris","Minaeve","Nadja","Niranye","Nirya","Raewyn","Selveni","Sera","Shaera","Siofra","Taarie","Tauriel","Valora","Valya","Vanadis","Vanora","Velanna","Ylthin","Ysayle","Yvraine","Zelda"];
    var elfLastName2 =  ["Aearonian"," Agaraen","Agarher","Agarvran","Aire","Airendil","Amamion","Amdirthor","Amathal","Amather","Amathuilos","Amatheldir ","Amlugol","Aessereg","Aupwe","Calear","Caranagar","Cemno","Duindaer","Duirro","Eilianther","Gaer","Galadher","Gollor","Gulduron","Guldur","Guldurion","Hithaerben","Holiilo","Ingolmondur","Lar","Leucandil","Lanthir","Loeg","Lo","Lumorndaer","Morguldir","Morgulon","Naur","Neithaor","Nullion","Olchanar","Othanar","Olerydon","Ranchon","Rimdor","Rodor","Roher","Rhovanion","Rhovanion","Ruina","Russarocco","Sir","Sirdhemion","Tawaren","Tawarenion","Tawarher","Tordil","Uirchanar","Urendur","Urucher","Yr"];
    var elfFemNameGenerator = capFirst(elfFemName1[getRandomInt(0, elfFemName1.length + 2)]) + " " + capFirst(elfLastName2[getRandomInt(0,elfLastName2.length +2)]);
    return elfFemNameGenerator;
}

//i want this to get the result's from "generateName" and it should be a global value so i can use it in the next function
var names = generateName();

// this should print the name at least ten times but no
function namePrinter(){
    var text = document.getElementById("textArea");

    for (var i = 0; i < 10; i++) {
      text[i].innerHTML(`${names}`)
    }
   return namePrinter;
}

Is there a way to wait for a function to load on page load in react native?

I’m developing a social network app and I’m trying to load the comments under each post. I’ve tried using async functions and the useEffect hook but it’s not working. Here is the code I’ve tried


    // get all comments for the current post
    const getComments = () => {
        async (dispatch) => {
        try {
            await db.collection('posts')
            .doc(postId)
            .collection('comments')
            .orderBy('timestamp', 'desc').onSnapshot(snapshot => {
                setComments(snapshot.docs.map(doc => doc.data()));
                console.log('Comments', snapshot.docs.map(doc => doc.data()));
            }
            )
        } catch (error) {
            console.log(error);
        }
    }
    }

  // load the current user, post ID and comments upon opening the screen
  useEffect(() => {
    getComments();
    getUser();
    getPostId();
  }, []);

The comments load in the console but do not get displayed unless I refresh the page while on it. Any ideas?

Find if RegEx matches exactly

I’m new to RegEx, and wanted to make an expression that checks if a date is formatted properly (in the format of “Mar 22, 2022”, for example).

This is the expression that I wrote:

const dateRegex = /[A-z][A-z][A-z]s([0-9][0-9]|[0-9]),s202[2-9]/g;

The problem is that although something like "Apr 24, 2022".match(dateRegex) works as needed, "Apr 24, 202222".match(dateRegex) matches with dateRegex and I don’t want it to.

Can anyone please suggest a way to either rewrite the RegEx or an alternative solution to this problem. Thank you.

How to properly write a javaScript toggle hide/show function for 2 forms (Registration and Login form) without refreshing a page or link to new html

I went through all similar questions but none of them seem to help me with what I want to do. Maybe I am just missing something and if there is a question out there that could help could you please point me to that question and I will delete this. Anywhoo…
I am trying to create a function that when I click a link on the bottom of the login form (Need an account? Register) it will hide the Login form and show the Registration form with a link on the bottom of the Registration form (Have an account? Login) to go back to the Login form without refreshing the page or going to a new html page.
I have tried multiple things… I want it to look like this… I have set the display to none for my registration form and the display for my login form to block.
example of login to registration and back

This is two of the codes I have tried.

Example one that seems right but is wrong:




function showAndHide(e) {
   const loginBtn = document.getElementById('loginbtn');
   const signupBtn = document.getElementById('signupbtn');
   const regForm = document.getElementById('register');
   const logForm = document.getElementById('login');
   if (regForm.style.display == 'none') {
       regForm.style.display = 'block';
       logForm.style.display = 'none';
   } else {
       logForm.style.display = 'block';
       regForm.style.display = 'none';
}
loginBtn.addEventListener('onclick', function(e) {
showAndHide(loginBtn);
});
signupBtn.addEventListener('onclick', function(e) {
showAndHide(signupBtn);
});    



Example two that seems right but is wrong:




function: showAndHide() {
  const regForm = document.getElementById('register');
  const logForm = document.getElementById('login');
  if (regForm.style.display = 'none') {
      regForm.style.display = 'block';
      logForm.style.display = 'none';
  } else { 
      logForm.style.display = 'none';
      regForm.style.display = 'block';
  }
}    



My Html:




 <body>
<section id="login">
    <h2>Login</h2>
    <form id="login-form" method="post" novalidate>
        <div>
            <label for="logfield">Email:</label>
            <input type="email" name="logfield" id="logfield" required>
        </div>
        <div>
            <label for="pw">Password:</label>
            <input type="password" name="pw" id="pw" size="15" required>
        </div>
        <div>
           <button type="submit">LOGIN</button>
        </div>
        <div>
            <a href="" id="signupbtn">Need an account? Register</a>
        </div>
    </form>
</section>
<section id="register">
    <h2>Register</h2>
    <form id="register-form" method="post" no validate>
        <div>
            <label for="email-field2">Email:</label>
            <input type="email" name="email-field2" id="email-field2" required>
        </div>
        <div>
            <label for="pw2">Password:</label>
            <input type="password" name="pw2" id="pw2" size="15" required>
        </div>
        <div>
            <label for="pw3">Repeat Password:</label>
            <input type="password" name="pw3" id="pw3" size="15" required>
        </div>
        <div>
            <button type="submit">REGISTER</button>
        </div>
        <div>
            <a href="" id="loginbtn">Have an account? Log in</a>
        </div>
    </form>
</section>
</body>    




Why I’m not getting the correct result when using map with reactJs?

I’m trying to get the content of my dynamic menu which is stored in database but when I’m using map I get nothing.
This is how I use the codition :

    {
              (userData && userData.user_type == 'o' && (menus.map((number) => number.menu_owner=='1')))
          
           &&
</>
}
                

I mean that if the user_type==’o’ I have to display menu’s content where menu_owner==’1′
Thanks in advance for anyone will try to help me

How can I tell where a shared module is loaded from when using module federation?

Let’s say I have five microfrontends, each of which has

    new ModuleFederationPlugin({
      shared: [{
        "foo": {
          singleton: true,
          eager: true,
          shareKey: "foo",
          import: "foo",
          shareScope: "default",
        }
      ]
    })

in their webpack config.

My understanding is that the browser will obtain “foo” from one of the microfrontends, and then all other microfrontends that request “foo” will just get the one that was already downloaded.

In the browser, is there any way of telling which microfrontend’s copy of “foo” is being used?

How to pass href parameter from parent vue component to child component?

Good evening!
I’m trying to create a page in Vue, parsing it into components, and rendering content using json. And it seems to be nothing complicated, but there is a problem.
But why is the href parameter in the wrong place? Please tell me, I have been unable to solve this riddle for several hours.

index.vue

<template>
  <section>
    <Hero
      v-for="(hero, index) in heroes"
      :title="hero.title"
      :description="hero.description"
      :more="hero.more"
      :href="hero.href"
      :key="index"
    />
  </section>
</template>

Hero.vue

<template>
  <div>
    <h2>{{ title }}</h2>
    <p>{{ description }}</p>
    <a :href="href">{{ more }}</a>
  </div>
</template>
<script>

Result

<section>
  <div href="/create">
    <h2>Create and share your photo stories.</h2>
    <p>
      Photosnap is a platform for photographers and visual storytellers. We make
      it easy to share photos, tell stories and connect with others.
    </p>
    <a>Get an Invite </a>
  </div>
  ...
</section>

My to do App is not deleting the list that is created?

Currently, I have the list created and when you click the check box the task gets scratched out to say that it is done. I have tried creating a function that deletes the list if the user has completed their task or just wants to remove it, however, the delete button is not working.

JS code:

let tasks = [];

const list = document.querySelector('.list')

//add a click event to the list and its elements tied to it
list.addEventListener('click', event =>{
  if(event.target.classList.contains('js-tick')){
  const itemKey = event.target.parentElement.dataset.key;
  toggleDone(itemKey);
}
  if (event.target.classList.contains('js-delete-todo')) {
    const itemKey = event.target.parentElement.dataset.key;
    deleteTodo(itemKey);
}

});

function  toggleDone(key)
{
  const index = tasks.findIndex(item => item.id === Number(key));

  tasks[index].checked =!tasks[index].checked;
  displaytasks(tasks[index]);
}

function deleteTodo(key) {

  const index = tasks.findIndex(item => item.id === Number(key));

  const todo = {
    deleted: true,
    ...tasks[index]
  };

  tasks = tasks.filter(item => item.id !== Number(key));
  renderTodo(todo);
}

The end result is that when the list is created, the user can also delete the list created.

Mock library with webpack

I’m attempting to replace a library for testing with webpack.

The code I want to change:

import foo from 'foo-lib'; // library dependency in package.json

I want this to import src/mock-foo.js instead.

This is for end-to-end tests, so I can’t use something like Jest mocks.

I have a development-only webpack.config. In that I’ve tried:

  resolve: {
    alias: {
      'foo-lib': path.resolve(__dirname, 'src/mock-foo.js')
    },
    extensions: ['.js'], // need this for some other aliases (not shown)
  },

I’ve also tried the older technique in the plugins array:

  new webpack.NormalModuleReplacementPlugin(
    /foo-lib/,
    'mock-foo.js'
  ),

as well as several variations on these.

I don’t get errors, but the original library loads every time.

Is this even possible? If so, what’s the correct syntax?

Can someone help me with this bug?

The problem is happening on the ball hits the middle of the right side on the beggining of the game. How can I fix that?
The problem is happening on the ball hits the middle of the right side on the beggining of the game. How can I fix that?

The problem is happening on the ball hits the middle of the right side on the beggining of the game. How can I fix that?

The problem is happening on the ball hits the middle of the right side on the beggining of the game. How can I fix that?

The problem is happening on the ball hits the middle of the right side on the beggining of the game. How can I fix that?

//Get Canvas
let canvas = document.querySelector("canvas"); //CHECK
let ctx = canvas.getContext("2d");

//Event Listener for the buttons
let bt1 = document.getElementById("bt1");
bt1.addEventListener("click", startGame);

let bt2 = document.getElementById("bt2");
bt2.addEventListener("click", pauseGame);

//Second step: Defining my variables here

let xBall = 400; //half of the widht of my canvas = 800
let yBall = 200; //half of the height of my canvas = 800
let sizeBall = 12; //diameter of the ping pong ball
let radiusBall = sizeBall / 2; //radius I am going to use this to mark the center of the ball
let speedXBall = 6; //speed of the ball for x coordenation.
let speedYBall = 6;

//level flags to adjust speed when its true.
let flag = true;
let flag2 = true;
let flag3 = true;
let flag4 = true;
//define variable for paddle position and size

let xpaddle = 0; //distance of paddle from the border of my canvas to X
let ypaddle = 160; // position y vertical
let paddleWidth = 10; //size racket in X direction
let paddleHeight = 70; // size racket in y direction

//define variable for opponent position and speed
let xOpponent = 790;
let yOpponent = 160;

//define variable for scores
let scorePlayer = 0;
let scoreOpponent = 0;

let interval;

//Start Game Buttton

ctx.fillStyle = "Press Start to begin";
ctx.font = "50px Verdana ";
ctx.fillText("Press Start to begin", 50, 200);
ctx.strokeText("Press Start to begin", 50, 200);

//Start Game Buttton
function startGame() {
  clearInterval(interval);

  clearCanvas();
  interval = setInterval(drawCanvas, 25);
}

//Pause Game Buttton
function pauseGame() {
  clearInterval(interval);
  clearCanvas();
  ctx.fillStyle = "#D9534F";
  ctx.font = "50px Verdana";
  ctx.fillText("Press Start to Unpause", 400, 200);
  ctx.strokeText("Press Start to Unpause", 400, 200);
}

//call functions that I want to show up on my canvas
function drawCanvas() {
  clearCanvas(); //allow me to draw in my screen and create the animation
  displayPoints();
  drawBall();
  moveBall();
  colisionBall();
  drawpaddle(xpaddle, ypaddle);
  drawpaddle(xOpponent, yOpponent);
  movepaddle();
  scorePoint();
  gameLevel();
  IsgameOver();
}

function clearCanvas() {
  //allow me to draw in my screen. Giving the ilusion of moviment
  ctx.fillStyle = " #006400";
  ctx.fillRect(0, 0, 800, 400); //position x,y and width/height) //my canvas is 800x400. Ball going behind screen /I noticed that I could change a little bit the 2 first numbers so the ball will go a little after my canvas and then score the point
  ctx.fillStyle = "white";
}

function drawBall() {
  //x,y position; radius; start angle end angle
  ctx.beginPath(); //mathPI clock direction
  ctx.arc(xBall, yBall, sizeBall, 0, 2 * Math.PI); //maybe use radiusBall instead of sizeball. But radius is too small
  ctx.fillStyle = "white";
  ctx.fill();
}

function moveBall() {
  xBall += speedXBall;
  yBall += speedYBall; //going to Y direction with Y speed
}

//CHANGE VELOCITY OF THE BALL 
function gameLevel() {
  if ((scorePlayer == 1 || scoreOpponent == 1) && flag) {
    speedXBall = 7;
    speedYBall = 7;
    flag = false;
  }

  if ((scorePlayer == 2 || scoreOpponent == 2) && flag2) {
    speedXBall = 10;
    speedYBall = 10;
    flag2 = false;
  }

  if ((scorePlayer == 3 || scoreOpponent == 3) && flag3) {
    speedXBall = 12;
    speedYBall = 12;
    flag3 = false;
  }

  if ((scorePlayer == 5 || scoreOpponent == 5) && flag4) {
    speedXBall = 13;
    speedYBall = 13;
    flag4 = false;
  }
}

function colisionBall() {
  //For the boders of my canvas

  if (xBall > canvas.width - radiusBall) {
    speedXBall *= -1; //will turn my values negative because I want to reverse the position
    xBall = 800;
  }
  //radius center of the ball
  if (yBall > canvas.height - radiusBall) {
    speedYBall *= -1;
    yBall = 394;
  }

  if (xBall < 0 + radiusBall) {
    speedXBall *= -1;
    xBall = 0;
  }
  if (yBall < 0 + radiusBall) {
    speedYBall *= -1;
    yBall = 0;
  }

  //for the paddle X
  if (
    xBall - radiusBall < xpaddle + paddleWidth &&
    yBall - radiusBall < ypaddle + paddleHeight &&
    yBall - radiusBall > ypaddle
  ) {
    speedXBall *= -1;
  }

  //for the paddle Y
  if (
    xBall + radiusBall > xOpponent &&
    yBall - radiusBall < yOpponent + paddleHeight &&
    yBall - radiusBall > yOpponent
  ) {
    speedXBall *= -1;
  }
}

function drawpaddle(x, y) {
  ctx.fillStyle = "white";
  ctx.fillRect(x, y, paddleWidth, paddleHeight);
}

function movepaddle() {
  onkeydown = (e) => {
    console.log(e.code);
    let key = e.code;

    //player 1
    if (key == "Numpad1") {
      yOpponent -= 10;
    }
    if (key == "Numpad2") {
      yOpponent += 10;
    }

    //player 2
    if (key == "KeyW") {
      ypaddle -= 10;
    }
    if (key == "KeyS") {
      ypaddle += 10;
    }
  };
}

function displayPoints() {
  ctx.font = "30px Arial";
  ctx.textAlign = "center";
  ctx.fillStyle = "red";
  ctx.fillRect(170, 20, 60, 40); //position x,y and width/height)
  ctx.fillRect(570, 20, 60, 40);
  ctx.fillStyle = "white";
  ctx.fillText(scorePlayer, 200, 50);
  ctx.fillText(scoreOpponent, 600, 50);
}

function scorePoint() {
  if (xBall < radiusBall) {
    scoreOpponent += 1;
  }
  if (xBall > canvas.width - radiusBall) {
    scorePlayer += 1;
  }
}

//gameover

function IsgameOver() {
  let gameOver = false;

  if (scoreOpponent == 6 || scorePlayer == 6) {
    gameOver = true;
  }

  if (gameOver && scoreOpponent > scorePlayer) {
    ctx.fillStyle = "red";
    ctx.font = "50px Verdana";
    ctx.fillText("Player 2 Win", 400, 200);
    ctx.strokeText("Player 2 Win", 400, 200);
    clearInterval(interval);
  }

  if (gameOver && scoreOpponent < scorePlayer) {
    ctx.fillStyle = "red";
    ctx.font = "50px Verdana";
    ctx.fillText("Player 1 Win", 400, 200);
    ctx.strokeText("Player 1 Win", 400, 200);
    clearInterval(interval);
  }

  return gameOver;
}

//implement reset button
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Ping Pong Match</title>
  </head>
  <style>
    h1 {
      font-family:'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
      text-align: center;
      padding-top: 30px;
      font-size: 40px;
    }

    h3 {
      font-family:'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
      
    }

    p{
      font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
      font-weight:100;
    }

    #bt1, #bt2 {
      color: rgb(57, 214, 57);
      background-color: rgb(46, 87, 74);
      font-family: 'Gill Sans', 'Gill Sans MT', 'Trebuchet MS', sans-serif;
      font-weight: bolder;
      font-size: larger;
      margin: 5px;
      padding: 3px;
      border-radius: 8%;
    }

    div{
      border: 2px solid green;
      text-align: center;
     margin-bottom:  300px;
     margin-left: 400px;
     margin-right: 400px;
     margin-top: 50px;
    }

  
    

  </style>
  <body>
    <canvas width="800" height="400"></canvas>
    <br />

    <input type="button" value="Start Match" id="bt1" />
    <input type="button" value="Pause Match" id="bt2" />
   <div>
    <h1>Instructions:</h1>
    <h3>How to move the paddle:</h3>
      <p>Player1 (Left) can move up and down using W and S. <br>
      Player2 (Right) can move up and down using the Numpad 1 and 2.</p>

      <h3>How to Start, Pause and Play Again:</h3>
      <p>To start the match press the button start. To pause press the button "Pause Match".<br>
      If you want to play again just reload the Page (F5).</p>

      <h3>How to Win: </h3>
      <p>Use strategies, have a good aim and reflexes. <br>
      The player who scores 6 points first Win the match. <br>
      So you must use your paddle to keep the ping pong ball far from your base
   </p>

   <h3>Speed of the ball:</h3>
   <p>Be alert: As the game progresses, the ball's speed will increse</p>

   <h1 div="tip"> THINK FAST!</h1>
  </div>
    <script src="teste copia.js"></script>
  </body>
</html>

How can I run this script from my website?

I’ve found this “STEAM hour booster” made in Node.JS (https://github.com/michikxd/hourbooster). I was thinking if there is any way to implement this into a website.

First time i thought that I can make for each user, a folder with the bot and config, and I’ve made a website, with login & register, but can’t run the bot since I can’t run a file on local computer from website…

I just only need a few suggestions, that can make this working.
Should I make a node.js server, then request things from my main site?

(I want to make this on a website, because I want to control it remotely, and give it to my friends too)

React avoid rerender of parent component when changing state from child component

I have this component:

const Parent = () => {
  const [a, setA] = useState({});

  return <Child setA={setA} />
}

const Child = ({ setA }) => {
  const [b, setB] = useState();
  const handleSomething = () => {
    setB({});
    setA({});
  }

  return b.map(etc => (...));
}

Basically, I want to avoid rerendering Parent component when a changes. Because this makes Child rerenders and it resets the internal state. How can I avoid it?

Navigating the JS DOM, parent child etc

Can someone please tell me why:

<tr>
    <td id="1"></td>
</tr>
        

is different then:

<tr><td id="1"></td></tr>
    

when it comes to navigate the DOM? My code:

event.target.parentElement....etc..

fails with “TypeError:cannot find property of null” if I edit the html page from the first example to the second.