Dynamically add html elements in react

Please how can I dynamically add html element (like span) to elements in a react component. I want to implement something like this



let text1 = '"Text one sentence.';
let text2 = 'Text two sentence'; 
const textElement1 = document.querySelector(".text-1");
const textElement2 = document.querySelector(".text-2");
let textSpan;

function setText(t) {
    t == text1 ? (textElement1.innerHTML = "") : (textElement2.innerHTML = "");
    t.split("").map((x) => {
        let charElement = document.createElement("span");
        let charNode = document.createTextNode(x);
        charElement.appendChild(charNode);
        t == text1
        ? textElement1.appendChild(charElement)
        : textElement2.appendChild(charElement);
    });
    textSpan = document.querySelectorAll("span");
    }


    function setFontWeight() {
    textSpan.forEach((element) => {
        let position = element.getBoundingClientRect();

        // Calculate The Distance Between Cursor And Target Elements
        let distance = Math.ceil(
        Math.sqrt((position.x - pointerX) ** 2 + (position.y - pointerY) ** 2)
        );

        // The Longer The Distance The Lower The Font Weight
        element.setAttribute(
        "style",
        `font-variation-settings: 'wght' ${900 - distance * 2};`
        );
    });
    }

This is the react component I have created

function TopSidePane(){
    
    return(
        <div onMouseMove={(e)=>Hover(e)} className="top-side-pane">
            <div className="text-container">
                <h1 className="text-1">{text1}</h1>
                <h1 className="text-2"> {text2}</h1>
                </div>
            <div className="custom-pointer" ></div>

        </div>
    );
}

Anytime there is a mouse movement on the component (if it get to the text inside the component) I want to be able to add span elements to the elements with the class names ‘text-1’ and ‘text-2’. After I add the elements, I call the setFontWeight to make the weight of the hovered letters bold.

Please any help on how to implement this in react. I am new to react.

what type do I use for app in express typescript

I’m exporting controllers in an index.ts, does anyone know what type do I use when passing app as a parameter in line 7?

import userController from "./userController.js"
import getController from "./getController.js"
import productController from "./productController.js"

const exportArr = [userController, getController, productController]

export default (app: any) => {
    exportArr.forEach(controller => controller(app))
}

Javascript works on desktop, but not on mobile

I am trying to take a number (user input) and then subtract that from another number (static value) and display the answer on screen. My code works fine on desktop, in any browser. The order qty displays on the screen as expected.

But it does not work on mobile, in any browser. The new number (order qty) never appears and is always left blank on mobile.

The only difference I know of vs mobile, is the user interface (touches, not keys or clicks). But I have tried many different event listeners, “touch”, “touchstart”, “input”, “blur”, and others i forgot. But that doesn’t seem to be the issue… nothing works.

Any idea why my page & code works perfect on desktop but has no effect on mobile? Here is my code:

{% extends "mobile_base.html" %} 
{% block content %}

<span class="mobile_large">Place order for: </span><span class="name">{{ name }} {{ dept}}</span><br><br>
<form name="order" action="/mobile_submit_order" onsubmit="return validateForm()" method="post">
    <label class="mobile_large" for="date_due">Delivery Date:</label>
<input type="date" id="date_due" name="date_due"><br><br>
    <input type="hidden" id="custId" name="custID" value="{{ customer }}">
    <table width="100%">    
<th>ITEM</th><th>On-hand</th><th>PAR<br>level</th><th>Order<br>qty</th>
{% for row in data %} 

<tr>
<input type="hidden" id="itemID" name="itemID" value="{{ row[1] }}">  
<td><label class = "mobile_large" for="item">{{ row[0] }}</label></td>
<td><input class="onhand mobile_large" type="number" pattern="d*" id="onhand-el{{ loop.index }}" min="0" max="9999"></td>
<td><p class="par mobile_large" id="par-el{{ loop.index }}">{{ row[2] }}</p></td>
<td><p class="total mobile_large" id="total-el{{ loop.index }}" name="frog"></p></td>
<input type="hidden" class="values" id="totalValue{{ loop.index }}" name="item">  
</tr>
{% endfor %} 
    </table><br> Customer Notes:<br>
    <textarea name="notes" rows="3" columns="50"></textarea><br><br>
    <input class="mobile_button" type="submit" value="Submit">
</form>

<script>
    myPars = document.getElementsByClassName("par")
    myOnHands = document.getElementsByClassName("onhand")
    myTotals = document.getElementsByClassName("total")
    myValues = document.getElementsByClassName("values")
    repeat = myPars.length

    for(let i=0; i<repeat; i++) {
        myOnHands[i].addEventListener("change", math)
        function math() {
            x = myPars[i].innerHTML
            y = myOnHands[i].value
            myTotals[i].innerHTML = x-y
            myValues[i].value = x-y
            if (myValues[i].value < 0) {
                myValues[i].value = 0
                myTotals[i].innerHTML = 0
            }  
        }
    } 
    
    function validateForm() {
         let x = document.forms["order"]["date_due"].value;
         if (x == "") {
             alert(" You must select a delivery date");
         return false;
   }
}
    
</script>
{% endblock %}

How to call a common function effectively whether synchronous or asynchronous function is executed using Promises?

I need to call a common function whether synchronous function is invoked or asynchronous function is invoked.

This is how I first wrote but this is not correct as foo will be called before asynchronous function is completed.

function main(element) {
  if (element.id === 'sync') {
    syncFunction();
  } else {
    asyncFunction();
  }
  foo();
}

So, I came up with this but here I feel like I am repeating the call to foo too many times. Is there a better way?

function main(element) {
  if (element.id === 'sync') {
    syncFunction();
    foo();
  } else {
    asyncFunction().then(() => {
      foo();
    });
  }
}

I could use async/await and refactor this even better but where this code eventually will run doesn’t support it. Is there a way to better write this using promises?

Js animation mouse stick

I understand animation and have a question how to do it like on this site https://katchme.fr enter image description here

so that on hover there is a similar effect of sticking to the cursor and increasing the block. At me it turns out to stick to the cursor but it is far from an ideal. Can you suggest the best way to do this?

maybe it’s easier to do it in vue but i didn’t find an example

all code https://codepen.io/Examp1/pen/dyoqLZE

(function () {
    'use strict';

    var boxElem = document.getElementById('box1');
    var pointerElem = document.getElementById('menu');

    function onMouseMove(event) {
        var mouseX = event.pageX;
        var mouseY = event.pageY;
        var crd = boxElem.getBoundingClientRect();
        var activePointer = crd.left <= mouseX && mouseX <= crd.right && crd.top <= mouseY && mouseY <= crd.bottom;

        requestAnimationFrame(function movePointer() {
            if (activePointer) {
                pointerElem.classList.remove('box-pointer-hidden');
                pointerElem.style.left = Math.floor(mouseX) + 'px';
                pointerElem.style.top = Math.floor(mouseY) + 'px';
            } else {
                pointerElem.classList.add('box-pointer-hidden');
            }
        });
    }

    function disablePointer() {
      pointerElem.style.left = "83px";
      pointerElem.style.top = "83px";
        requestAnimationFrame(function hidePointer() {
            pointerElem.classList.add('box-pointer-hidden');
        });
    }

    boxElem.addEventListener('mousemove', onMouseMove, false);
    boxElem.addEventListener('mouseleave', disablePointer, false);

})();

JavaScript: return true from the function if onload inside returns true [duplicate]

I have function, that sends request to create encrypted cookie. Inside that function there is onload function.

What I need?
I need to “transfer” return from onload() to parent function.

function createCookie(method = "POST", action, parameters, token, contentType = "application/x-www-form-urlencoded") {
    let xhr = new XMLHttpRequest();
    xhr.open(method, action, true);
    xhr.setRequestHeader('Content-type', contentType);
    xhr.onload = () => {
        let jsonResponse = JSON.parse(xhr.responseText);
        if(jsonResponse && jsonResponse['status'] == 'true') {
            return true;
        } else {
            return false;
        }
    }
    xhr.send("_token=" + token + "&" + parameters);
}

How to send multiple req.body inputs in a nodemailer email?

I am building a contact form with multiple input lines, and would like information from the form to be sent to my email address. For instance, I have a line for the user’s email address, a line for the user’s budget, and a line for the user’s city. These variables are denoted by “email”, “budget”, and “city”, respectively. As a result, I am using req.body.email as the text in nodemailer.

The issue is that I am only able to put one of the variables in the text section of the email. Here is my code to better explain what I mean.

const mailOptions = {
from: req.body.email,
to: '[email protected]',
subject: 'New message from Ogma',
text: req.body.email
    }

What is the syntax I have to use in order to also put req.body.budget and req.body.city in the text section?

Thank you!

second button delay after first button is clicked

So basically for fun I am making a spooky website. Once the user clicks on the enter button a scary face pops up. After 3 seconds of the image popping up I want another button that says “Continue” so the user can go on to the next html page but have no clue on how to do so. I am not great with Javascript or Jquery. Here is all I have so far….

    <html>
     <head>
     <meta name="viewport" content="width=device-width, initial-scale=1">
     <style>
      .header {
      justify-content: center;
      text-align: center;
      font-size: 170%; 
      color: black;
    font-family: Papyrus;
      
}

* {
  margin: 0;
  box-sizing: border-box;
}

body {
   padding: 70px 200px;
   margin: 59px;
   background-position: center top;
   background-repeat: no-repeat;
   background-image: url("https://i.postimg.cc/13dfXzBt/Shadow-Men.jpg");
   background-size: 950px 1000px;
   background-color: #000000;
}

button {
  background-color: red;
  border: none;
  color: black;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: block;
  font-size: 16px;
  font-family: Papyrus;
  font-weight : bold ;
  margin: 0 auto;
  cursor: pointer;
  position: center;
  justify-content: center;
}


#jumpscare{
position:absolute;
top:0px;
left:0px;
width:100%;
height:100%;
visibility:hidden;
}


</style>


<body>

<div class="header">
     <h1><span style="color:red">T</span>he <span style="color:red">E</span>xorcist <span style="color:red">H</span>ouse</h1>
    </div>  
    
<button onclick="jumpscare();"> Enter </button>
<img id="jumpscare" src="img_scaryface.jpg"/>

<script>
function jumpscare(){
var jumpscare = document.getElementById("jumpscare");
jumpscare.style.visibility="visible";
}

</script>

 </body>  
</html>

Cannot use import statement outside a module CLIENT-SIDE

At client-side, I want to import only a specific part of my Javascript module.
But I wanna do that on demand, like when a user performs an action that needs that specific part of the module.
I was able to accomplish that in the HTML file, with:

<script type="module">
 import { sayHi } from "/public/js/sayHi.js";
 sayHi("John");
</script>

Now I want to do the same but in my client-side JS file, so that I run this loading whenever I want (and not on page load, as in the example above). The closest that I got from solving it was running this in my client-side JS file:

import("/public/js/sayHi.js")

But the problem is that this last script loads the whole module, not just the part that I want. If I try to do this:

import { sayHi } from "./sayHi.js";

I get the error “Cannot use import statement outside a module”.

How can I import only the { sayHi } part via my client-side JS?

P.S.: Just to give an example, I would like to have something like that in my client-side JS:

buttonX.addEventListener('click', async () => {
  const a = await import { sayHi } from "./sayHi.js";;
});

keep getting an error when i try to run node boilerplate [duplicate]

The following code produces this type error when run with Node

TypeError [ERR_INVALID_ARG_TYPE]: The “data” argument must be of type
string or an instance of Buffer, TypedArray, or DataView. Received
undefined

It works when run with an undisclosed older version. Please help

const fs = require('fs');
const folderName = process.argv[2] || 'Project'

fs.mkdirSync(folderName);
fs.writeFileSync(`${folderName}/index.html`)
fs.writeFileSync(`${folderName}/app.js`)
fs.writeFileSync(`${folderName}/styles.css`)

I am trying to return object from function but it returns nothing any idea?

function getAllUsers1 (){
  var con = new sql.connect(config,(err)=>{ 
    if(err){
      console.log(err)
      return err ;
    }else{
      console.log('1');
      con.query("select * from WebMail_Send", function (err,data){
        if(err){
          console.log('invaled query..............');
          return err ;
        }else{
          console.log(data);
          return data;
        }
      })
    }
  });
}    
router.get('/sql',(req,res,next)=>{   
  var getAllUsers = new getAllUsers1();             
  res.render('sql', { items: getAllUsers})
});

No Error but return nothing

I’m trying to get data from SQL DB and display it on the HBS page.

How to increse a quantity in a cart without refreshing the page? i am using put method for fetching the data from mongodb

const handleRestock = (quantity) => {
if (quantityRef.current.value) {
const updatedQuantity =
parseInt(quantity) + parseInt(quantityRef.current.value);

        const newQuantity = { updatedQuantity };

        fetch(`http://localhost:5000/item/${itemId}`, {
            method: "PUT",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify(newQuantity),
        })
            .then((res) => res.json())
            .then((data) => {
                if (data.modifiedCount > 0) {
                    const updatedItem = {
                        
                        quantity: updatedQuantity,
                    };
                    setItem(updatedItem);
                    
                    toast("Restocked successfully", { type: "default" });
                }
            });
    }
};

Algorithm to get maximum affordable amount of items with individual costs and limits

i got a small headache over a problem regarding an efficient way to distribute a fixed amount of points evenly between n items that got different costs and limits. Costs don’t increase with each item.

Lets say i got 3 Items:

Name Cost Limit
A 25 220
B 30 20
C 50 60

Further we got fixed Points: 5000.
I want to know how many times i can buy each.
My curent solution runs a loop and deducts the cost from points until either all limits are reached or points ran out.
http://jsfiddle.net/nasc8rfL/



var points = 5000;
var costA = 25;
var costB = 30;
...

var limitA = 220;
...

var maxA = 0;

while (points > 0){
   if (points >= costA && limitA > 0){
     points -=costA;
     limitA -=1;
     maxA +=1;
   };
   if (points >= costB && limitB > 0){
     points -=costB;
     limitB -=1;
     maxB +=1;
   };
   if (points >= costC && limitC > 0){
     points -=costC;
     limitC -=1;
     maxC +=1;
   };
   if((points < costA) and (points < costB) and (points <costC)) break; 
}    

console.log(maxA,maxB,maxC);


Eventually it will not stay at A,B,C but variable number of elements(not more than 20) so i’d loop through each element instead of 3 IFs.

I dont actually have to deduct points i just have to know how many of each item can be bought. I feel like im missing something and there is an easier way to determine the number of each.

I’ve thought about weighting them based on their limits but my head doesnt want to work with me and im pretty stuck right now.

In addition im a beginner in javascript, so if you guys got some tips to get the shown loop faster or more convinient maybe with something like

function func(arr){
  arr.forEach(x=>{doSomething();})

i would be more than happy.

Best way to handle Svelte component props

I’m building an app using SvelteKit and Tailwind. I know that when using Tailwind to style it is recommended to leverage components to reduce the amount of repeated code you have to write using Tailwinds utility classes. My issue is that when making components based on HTML tags, for instance an <input> tag, dealing with props in that component that would normally just be attributes for that tag is getting overwhelming. MDN shows that the <input> tag has 31 possible attributes. I know that I won’t be using all of them but going back and forth and adding them as props to a component is getting tiresome.

What is the best way to solve this problem without adding up to 31 lines of export let attribute to a component and adding them to the real HTML tag inside of the component?

Example:

<script>
    export let name;
    export let id;
    export let type;
    export let disabled;
    export let required;
    export let minLength;
    export let maxLength;
    export let min;
    export let max;
    export let pattern;

    let value;
    let borderColor = '#D1D5DB';

    const inputHandler = (e) => {
        if (e.target.value === '') {
            borderColor = '#D1D5DB';
        } else {
            borderColor = '';
        }
    };
</script>

<input
    {name}
    {id}
    {type}
    {disabled}
    {required}
    {minLength}
    {maxLength}
    {min}
    {max}
    {pattern}
    on:input={inputHandler}
    style={`border-color: ${borderColor}`}
    class="
    w-full px-1 py-px mb-4 bg-transparent border-2 border-gray-300 
    rounded-xl last:mb-0 valid:border-emerald-300 invalid:border-rose-400
  "
/>