Ripple effect in the useState when I try to use it to store an element in an Array

Background

I am trying to do this challenge (please refer to the screenshot below) where I have to replicate the Kanban Board. Here is the link to the challenge

enter image description here

But I am stuck.
First off, here is what I mean by the Ripple Effect:

In the modal under the columns section, I want to store each entry in the input into an array that is managed by useState(). However, when I do so, each letter of the array gets stored separately.

enter image description here

Here is the code for the form that I have embedded in a modal. I am not using Context:

import {useState } from 'react';

// importing styles
import ‘../styles/Modal.css’;

const NewBoardForm = ({setTabs, modalHandler, tabs, handleTabs, handleBoardColumns }) => {

const [allColumns, setAllColumns] = useState([]);
const [name, setName ] = useState([]);
const [board, setBoard] = useState('');






// the function that adds column inside the sidebar form
const addColumn = (event) => {
    setAllColumns([...allColumns, <input className='columnsInput'  onChange={(e)=>{ setName(old=>{return [...old, e.target.value]})}} type="text"  />])
    console.log(name)
}   



const formReset= () => {
    setAllColumns([]);
    setName([]);
    setBoard('');
}


// get the data from the form

const getData = (event )=>{
    event.preventDefault();
    
    const tabsInput={
        title: board,
        id: Math.floor(Math.random() * 1000) + 1
    }


    const boardColumns = {
        title: name,
        id: Math.floor(Math.random() * 1000) + 1,
    }

    console.log(name)

    handleBoardColumns(boardColumns);

    console.log(board)


    handleTabs(tabsInput);

    
   

    modalHandler();
    formReset();
}




return ( 
// form starts from here
    <>
    <form className="boardForm" >
        
        <label>
            
            <span className='name'> Board Name</span>
            <input className='nameInput' type="text" onChange={e=>setBoard(e.target.value)}/>

            
        </label>

        {/* new section for columns */}

       

                
                    <span className='columns'>Columns</span>
                    {allColumns.map((column) => {
                        return (
                            
                            <label className='addNewColumn' >
                                {column}
                            </label>
                            
                            
                        )
                    })}
               


                <button onClick={e=>{
                    e.preventDefault();
                    addColumn();
                }} className='addColumnBtn' type="button">+ Add Column</button>


       

        {/* section for columns ends here */}

        <button className='close-btn' onClick={getData}  type="submit">Create New Board</button>

    </form>
    
    {/* form ends here */}


    </>
 );

}

export default NewBoardForm;

Here is the link to the Github Repo:

GitHub Repository

The transaction fails when using the SDK, but succeeds when using the REST API

I have created a checkout order using sumup-ecom-php-sdk.
So I got the checkoutId from the response.

$sumup = new SumUpSumUp([
  'app_id' => '...',
  'app_secret' => '...',
  'grant_type' => 'client_credentials',
]);

$checkoutService = $sumup->getCheckoutService();
$amount = floatval(str_replace(',', '.', str_replace('.', '', $invoice->total)));
$currency = 'EUR';
$checkoutRef = $invoice->number;
$payToEmail = "[email protected]";
$description = 'Test';

$checkoutResponse = $checkoutService->create($amount, $currency, $checkoutRef, $payToEmail, $description);
$checkoutId = $checkoutResponse->getBody()->id;

I developed the payment page using the sumup-card widget sdk and loaded the sumup-card using the checkoutId obtained above.

@extends('layout.app_layout_client')

@section('body')
    <div id="sumup-card">
    </div>

    <script>
        const checkoutId = @json($checkoutId);

        var sumupCard = SumUpCard.mount({
            checkoutId: checkoutId,
            showAmount: true,
            showFooter: true,
            currency: "EUR",
            locale: "de-DE",
            onResponse: function (type, body) {
                if (type == "success") {
                    console.log(body);
                    $.ajax({
                        url: "/sumup/checkout/complete",
                        type: "PUT",
                        data: {
                            checkoutId: checkoutId,
                        },
                        dataType: "json",
                        success: function(res) {
                            if (res.success) {
                                window.location.href = res.redirectUrl;
                            } else {
                                console.log(res.message);
                            }
                        },
                        error: function(error) {
                            console.log("Network Error");
                        }
                    });
                } else {
                    console.log(type);
                }
            },
        });
    </script>
@endsection

But when I submit the sumup-card form, the transaction always fails.
The result is like the following:

{
  "id": "fc0361f0-9689-4eff-89d2-bf138665e494",
  "reference": "23/2352",
  "amount": 119,
  "status": "FAILED",
  "currency": "EUR",
  "description": "Test Checkout",
  "merchant": {
    "code": "..."
  },
  "current_payment": {
    "id": "3510b833-4998-4edd-aeec-ab17780ec5b7",
    "transaction_code": "TCAKA4PQSD",
    "status": "failed",
    "created_at": "2023-04-08T01:33:29+00:00",
    "updated_at": "2023-04-08T01:33:30+00:00"
  }
}

On the other hand, if the checkout is handled through the REST API rather than the sumup-card widget, the transaction succeeds.

$customService = $sumup->getCustomService();
$customResponse = $customService->request('PUT', '/v0.1/checkouts/'.$checkoutId, [
  "payment_type" => "card",
  "card" => [
     "name" => "Dominik Biermann",
     "number" => "4242424242424242",
     "expiry_month" => "12",
     "expiry_year" => "34",
     "cvv" => "123"
  ]
]);
dd($customResponse);

I should implement via SDK. How can I fix it?

PHP gets empty data from AJAX

I would like to create a simple “Deselect All” functionality on a filter-based selection. I read on the Internet that AJAX would be a perfect tool for it so I dove in to code, but I can’t seem to get any data from the AJAX data field.

Just to clarify, I am totally new to AJAX and somewhat proficient with PHP.

This is my script function that is triggered by clicking on a clickable HTML element. What I am trying to do is pass the data to PHP so that it knows which filter field to deselect and clear.

script.js

$(document).ready(function(){
    $("#sport").click(function(){
        $.ajax({
            method: "POST",
            url: "ajax.php",
            data: {filter: "sport"},
            dataType: "text",
            success: function(data){
                alert("Success: " + data);
            },
            error: function(){
                alert("Error");
            }
        });
    });
});

This above snippet works on click as I am getting the alert window in browser.

This below is my PHP test file with which I am trying to get the data posted by my AJAX function:

ajax.php

<?php
    $filter = $_GET['filter'];
    echo $filter;
?>

I have tried multiple dataTypes in the AJAX function, but I either kept getting “null” from json or empty string from “text”. Then when I tried creating a random array within ajax.php, that worked fine using json_encode().

This only alerts “Success: ” instead of “Success: sport” as I would expect. Can anybody help me understand please?

Uncaught TypeError: Cannot set properties of undefined (setting ‘nearestColor’) at nearestColor.js:400:26 at nearestColor.js:403:2

Im trying to import ‘nearestColor’ from this module ‘https://cdn.jsdelivr.net/gh/dtao/nearest-color@master/nearestColor.js’ in my javascript file but it keeps giving me this error.
Uncaught TypeError: Cannot set properties of undefined (setting ‘nearestColor’)
at nearestColor.js: 400:26
at nearestColor.js: 403:2

if (typeof module === 'object' && module && module.exports) {
    module.exports = nearestColor;
  } else {
    context.nearestColor = nearestColor;
  }

}(this));
export default nearestColor;

I tried removing the else statement but it gave me this error instead
Uncaught ReferenceError: nearestColor is not defined
at nearestColor.js:401:16

Does anyone know how to fix it?

Vuejs 3 v-tables-3 customize filter text

I’m learning Vue 3 and I’m using vue3-tables. I read the documentation, but I don’t find any example on how to customise the filter text. In the table header there is text input to filter content of the column and want to customize the default text : Filter by [Column name].

My use case is very simple:

<v-client-table :data="items1" :columns="columns1" :options="table_option">
                            <template #action="props">
                                <div class="actions text-center">
                                    <a href="javascript:void(0);" @click="openUser(props.row)" class="edit">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24"
                                             viewBox="0 0 24 24" fill="none" stroke="currentColor"
                                             stroke-width="2"
                                             stroke-linecap="round" stroke-linejoin="round"
                                             class="feather feather-edit"
                                             data-v-b121048b="">
                                            <path
                                                d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
                                            <path
                                                d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
                                        </svg>
                                    </a>
                                    |
                                    <a href="javascript:void(0);" @click="openUser(props.row)" class="cancel">
                                        <svg
                                            xmlns="http://www.w3.org/2000/svg"
                                            width="24"
                                            height="24"
                                            viewBox="0 0 24 24"
                                            fill="none"
                                            stroke="currentColor"
                                            stroke-width="1.5"
                                            stroke-linecap="round"
                                            stroke-linejoin="round"
                                            class="feather feather-x-circle table-cancel"
                                        >
                                            <circle cx="12" cy="12" r="10"></circle>
                                            <line x1="15" y1="9" x2="9" y2="15"></line>
                                            <line x1="9" y1="9" x2="15" y2="15"></line>
                                        </svg>
                                    </a>
                                </div>
                            </template>
                        </v-client-table>

The code :

const items1 = ref([]);
    const columns1 = ref(["FirstName", "LastName", "action"]);

    // let dt;
    const table_option = ref({

        perPage: 10,
        perPageValues: [5, 10, 20, 50],
        skin: "table table-striped",
        columnsClasses: {

            action: "actions text-center"
        },

        headings: {

            FirstName: firstName,
            LastName: lastName,
            action: "",
        },

        pagination: {

            nav: "scroll",
            chunk: 5
        },

        texts: {

            count: t("Results") + " {from} " + t("of") + " {to}, " + t("Total") + " : {count}",
            filter: "",
            filterPlaceholder: t("Search"),
            limit: "Results:",
        },

        resizableColumns: false,

        sortable: ["FirstName", "LastName"],

        sortIcon: {

            base: "sort-icon-none",
            up: "sort-icon-asc",
            down: "sort-icon-desc",
        },

        filterByColumn: true,
        filterable: ["FirstName", "LastName"]
    });

    onMounted(() => {

        getUsers().then(() => {

            items1.value = users.value;
        }).catch(error => {

            console.log(error);
        });
    });

    const openUser = (item) => {

        router.push("/user/" + item.ID);
        // alert("ID: " + item.ID + ", Name: " + item.FirstName + " " + item.LastName);
    };

Any help will appreciated.

Thank you.

HTML TABLES: Is there a way to set a table to add another column for td after a certain number of rows? [closed]

I’m working on a web app where the user sees a list of channels to join displayed as a table. Is there a way to make the table add another column after a certain number of rows? It’s not a problem right now but after a while the list of channels will be very long so I’d prefer it break it out into another column with smaller number of rows.

So far I havent really tried anything besides searching SO/codepen

How can I create a new CSV file with the row and column numbers from each cell in JavaScript?

Some of you may find this question easy. However, I am a navie in JavaScript. I have a CSV file [find the CSV file here] without header information. Each cell in the CSV file contains some values. So I want to walk through all of those cells’ rows and columns and save the cell values as well as the accompanying row and column numbers in a separate csv file. I have to do it in JavaScript.

For those who are unable to download the CSV file, I have cut that section and put it here.

enter image description here

My goal is to get below result in a new csv file.

row column value

1 1 0.704191104

1 2 0.424829561

1 3 0.009920801

….

12 1 0.337513255

12 2 0.435984561

….

12 7 0.546245968

Any help will be highly appreciated.

I tried like below but didn’t work.

RawData = d3.csvParse(
  await FileAttachment("datafile.csv").text(),
  d3.autoType
)
d3 = require('d3-dsv')

How to use JS library inside an Angular 13 project

I am using an SDK, and it’s only available as a Javascript library. I am using Angular 13 and I need to use this library, because it’s the only way for me to use the service. I’ve tried to import the library js file in the index.html and also tried to include it in angular.json’s scripts section, no success.

I need to instantiate an object out of that library. Intellisense tells me it doesn’t exit.

const MercadoPago = new MercadoPago(); 

The Library in question is this

https://sdk.mercadopago.com/js/v2

Keeping an object in an absolute position similar to display flex justify and align

I aligned a button with an object of my background image. Sadly the object isn’t exactly in the middle of the background image, so I have to use position absolute to position my button.
If the screen size changes, my button moves and does not align with the element of the backgroud anymore.
I want my button to behave as if I used flexbox with justify content and align items center, keeping it in the relativly same position.
Another problem is that my button will become bigger than the screen width on mobile devices messing up the background.
I assume that I have to use javascript to keep track of the display and background size and change the position, as well as changing the button size? Is there a possibility to hide the buttons overflow similar to an images overflow?
I would be very thankfull for ideas/ solutions.

<div class="background_container">
      <button type="button" id="button_deploy" class="btn btn-outline-light">DEPLOY</button>
</div>
.background_container{
    background-color: rgb(15, 15, 15);
    height: 100vh;
    background-image: url(./media/img/gatetrium_sgp.jpg);
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
    
}

#button_deploy{
    position: absolute;
    top: 30.3vh;
    left: 39.8vw;
    width: 432px;
    height: 432px;
    font-weight: 700;
    font-size: 36px;
    color: rgba(26, 0, 0, 0.793);
    border-color: transparent;
    border-radius: 50%;
        &:hover{
            background-color: rgba(121, 201, 255, 0.186);
            //box-shadow: 0 0 20px 10px rgba(121, 201, 255, 0.186);
        }
}

Here are some images to visualize the problem.

how it's supposed to look like

what happens if the display size changes

the issue with mobile devices

how to handle errors in Fetch javascript

I have an error handling code that works perfectly fine but shows those red errors in the console.
I tried the .catch() functions but it did not work, the error still shows and the code inside the .catch() also doesn’t run

Here’s the working code:

function getData(key) {
fetch(key)
    .then(res => {
        if (res.ok === false) {
            res.json()
                .then(e => {
                    alert(e.message)
                })
        }
        else {
            res.json()
        }
    })
    .then(json => {
        data = json;
    })

}

I’m just trying to display the error message to the user without those console errors.

AWS API Gateway CORS console enabled but still getting Response to preflight request doesn’t pass …No ‘Access-Control-Allow-Origin’ header

I create an api from api gateway with a get and a put method, I have enabled the CORS from console and deployed the api, then generated javascript SDK.
In my codes I try to establish connection through apigClient.js connect keeps failling

    var body = { };
    var params = {bucket: 'my-bucket-name', filename: 'my-image.jpg'};
    var additionalParams = {headers: {
    "Access-Control-Allow-Origin": "*",
    'content-Type':"application/json"
    }};

    apigClient.bucketFilenameGet(params, body , additionalParams).then(function(res){
        console.log("connection successful")
        showImages(res.data)
      }).catch(function(result){
          console.log("connection failed")
      });

This is my method response it access through a lambda function and does not require api key
enter image description here

The lambda function access a S3 bucket, this is the bucket CORS permission
enter image description here

I’m able to use postman to perform both GET and PUT request, but when I try to initiate the api gateway from the above codes, I keep getting the error on chrome.

Access to XMLHttpRequest at 
'https://xxxxx.execute-api.us-east-1.amazonaws.com/prod/my-bucket-name/my-image.jpg' 
from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check: 
No 'Access-Control-Allow-Origin' header is present on the requested resource.

I tried to use command to disable chrome’s CORS and restart the browser but did not work

open /Applications/Google Chrome.app --args --user-data-dir="/var/tmp/chrome-dev-disabled-security" --disable-web-security --disable-site-isolation-trials

Not sure what to do at this point.

is there an easy way to read a file on Cypress and make an array out of it

I have tried using readFile, readFileSync, and I get errors like readFileSync is not a function.

I have fs imported but not sure what I am missing.

Cypress is using Javascript and i dont see why it wont work.

Reading a file which looks like this and saving contents as an array

banana
apples
oranges

[‘bananas’, ‘apples’, ‘oranges’]

I have tried using readFile, readFileSync, and I get errors like readFileSync is not a function.

I have fs imported but not sure what I am missing.

Cypress is using Javascript and i dont see why it wont work.

Reading a file which looks like this and saving contents as an array

banana
apples
oranges

[‘bananas’, ‘apples’, ‘oranges’]

Javascript works only partially or it doesn’t at all

I’m very green and I’m just trying to patch together different pieces of code to pass a test (to be accepted into an Software Development Apprenticeship). I’ve found that my Javascript works less if all the functions are in the same file and even dividing them, not all of them work or work properly: one that is supposed to change the whole page to shades of grey, but works only on the wireframe instead of the whole ; one that is supposed to change the “Name” textbox to pink when clicking out (if the content is invalid) doesn’t work at all (I tried doing it on CSS as well, but it gives me pink textboxes from the start, which is not part of the requirements); one that translates some strings, does it to all except the bottom two. The only one that seems to be working fine (if the JS is in a separate file) is the captcha one. On top of that, I commented out certain things that’d make everything look weird and for what I couldn’t find a fix (for example, next to the “Providers” I wanted a radio multiple choice). Could you please help me? It’s not adamant that everything is perfect, but I don’t want to burn my chances presenting a terrible product, even though this is not what the Apprenticeship is about.

This is my HTML:

<!DOCTYPE html>
<html lang="en", "it", "es">
<head>
    <title data-mlr-text>Validation Page</title>
    <link rel="icon" type="image/x-icon" href="favicon.ico">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!--I used ANSI instead of UTF-8 to incorporate all the possible variations of letters for the Name form-->
    <meta charset="ANSI">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
        <link rel="stylesheet" type="text/css" href="captcha.css">
        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.3/css/all.css" integrity="sha384-SZXxX4whJ79/gErwcOYf+zWLeJdY/qpuqC4cAa9rOGUstPomtqpuNWT9wdPEn2fk" crossorigin="anonymous">
    <link rel="stylesheet" href="softwareDevTechnicalChallenge_TaskOne_Development.css">
        <script src="captcha.js"></script>
    <!--I divided the JS files and linked them separately, because I had some issue with some code and it felt better in working on them separately-->

</head>

<body onload="generate()">
    <br>
    <br>
    <br>
    <div id="wireframe">
        <form>
            <!--action="mailto:[email protected]" method="POST" enctype="multipart/form-data" name="EmailForm"-->
            <div class="settings">
            
                    <!--Name and surname input-->
                    <label for="name" data-mlr-text>Name</label>
                    <input type="text" id="nameBox" placeholder="Write your full name here" title="Write your full name" pattern="w{1,747}" required onfocusout=validateName()>

                    <!--Email input; I figured an email couldn't be smaller than 5 characters, even minimized like [email protected]>
                    <label for="email" data-mlr-text>Email</label>
                    <input type="email" id:"email" name="email" placeholder="Write your email address here" title="Write your email address" maxlength="345" minlength="5" required>

                    <!--Card provider choice-->
                    <label for="provider" title="Choose your Debit/Credit Card's provider" data-mlr-text>Provider</label><br>
                        <!-- Commented out because it messes with the formatting and sizes
                        <input type="radio" id="visa" name="card_providers" value="Visa">
                        <label for="visa">Visa</label>
                        <input type="radio" id="mastercard" name="card_provider" value="Mastercard">
                        <label for="mastercard">Mastercard</label>
                        <input type="radio" id="americanexpress" name="card_provider" value="American Express">
                        <label for="americanexpress">American Express</label>-->

                    <!--Debit/Credit Card input; I set the type to password as an added layer of security-->
                    <label for="card" data-mlr-text>Card</label>
                    <input type="password" placeholder="Write your Credit/Debit Card here" title="Write your Credit/Debit Card number" pattern="d{10,19}" required>

                    <!--CVV/CVC input-->
                    <label for="cvv">CVV/CVC</label>
                    <input type="text" placeholder="CVV/CVC" title="Write the security number on the back of your card" pattern="d{3,4}" required><br>

                    <div id="user-input" class="inline">
                            <input type="text" id="submit" placeholder="Captcha code" required/>
                        </div>
 
                        <div class="inline" onclick="generate()">
                            <i class="fas fa-sync"></i>
                        </div>
 
                        <div id="image" class="inline" selectable="False">
                        </div>
 
                        <p id="key"></p>

            </div>
                <!--do the button with an Alt text and the captcha-->
                <div class="button">
                    <input type="submit" class="button" value="Submit" type="submit" title="Click to submit your credentials!">
                </div>

            
    </div>
        </form>
    <br>
    <br>
    <br>
    <br>
    <br>
    
    <div id="footer">
        <hr>
        <form>
            <div id="footer1">
                <!--To view the page with shades of grey-->
                <p name="gshades" title="Click to see the page in shades of grey" onclick="shadesOfGrey()" data-mlr-text>View in Greys</p>
            </div>

            <div id="footer2">
                <!--To view the page in another languages-->
                
                <label for="language" title="Choose another language" data-mlr-text>Change Language</label>
                <select name="language" class="mb-POCControls_Selector" id="mbPOCControlsLangDrop">
                    <option value="en">English</option>
                    <option value="it">Italiano</option>
                    <option value="es">Español</option>
                </select>

            </div>
        </form>
    </div>
<script src="softwareDevTechnicalChallenge_TaskOne_Development_3.js"></script>
<script src="softwareDevTechnicalChallenge_TaskOne_Development.js"></script>
<script src="softwareDevTechnicalChallenge_TaskOne_Development_2.js"></script>
<script src="softwareDevTechnicalChallenge_TaskOne_Development_4.js"></script>
</body>
</html>

This is my CSS:

body {  
    /*setting the green colour per request, just semi-transparent to highlight the wireframe*/
    background-color: rgba(137, 200, 46, .5);
    text-align: center;
    font-size: 18px;
    font-family: calibri;
    color: rgba(60, 60, 59);
}

.button {
    background-color: rgba(231, 0, 100);
    border: 1px;
    color: rgba(60, 60, 59);
    padding: 4px 12px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    margin: 2px 1px;
    cursor: pointer;
    border-radius: 35px;
    font-size: 18px;
    font-family: calibri;
}

#wireframe {
    background-color: rgba(137, 200, 46);
    padding: 10px;
    border-radius: 25px;
    border: 4px solid #3c3c3b;
    width: 400px;
    margin: auto;
}

/*this is going to be the wrapper for the two footers; I'm dividing them in case I want to do different things with them*/
#footer {
    position: fixed;
    bottom: 0;
    text-align: center;
    width: 100%;
    margin: auto;
    overflow: auto;
}

#footer1 {
        padding: 5px;
    float: left;
    position: sticky;
    left: 500px;
}

#footer2 {
        padding: 23px;
    float: right;
    position: sticky;
    right: 400px;
}

/*As with the body bg colour, the hr is semi-transparent*/
hr {
    display: block;
    margin-top: 0.5em;
    margin-bottom: -1%;
    margin-left: auto;
    margin-right: auto;
    border-style: dashed;
    border-width: 1px;
    color: rgba(60, 60, 59, .5);
}

div.settings {
    display: grid; 
    grid-template-columns: 96.7px 203.3px; 
    grid-template-rows: 33.3px 33.3px 33.3px 33.3px 33.3px; 
    gap: 10px 43px; 
    grid-template-areas: 
        ". ."
        ". ."
        ". ."
        ". ."
        ". ."; 
}

div.settings label { 
    text-align: right; 
}

div.settings label:after { 
    content: ":"; 
}

input[type=text] {
    width: max;
}

#image {
    margin-top: 10px;
    box-shadow: 3px 3px 3px 3px gray;
    width: 60px;
    padding: 20px;
    font-weight: 400;
    padding-bottom: 0px;
    height: 40px;
    user-select: none;
    text-decoration:line-through;
    font-style: italic;
    font-family: Calibri;
    border: red 2px solid;
    margin-left: 10px;
     
}

#user-input {
    box-shadow: 3px 3px 3px 3px #3c3c3b;
    width:auto;
        margin-right: 10px;
    padding: 10px;
    padding-bottom: 0px;
    height: 40px;
        border: #700064 0px solid;
}
input {
    border:1px #3c3c3b solid;

}
.inline {
    display:inline-block;

}

/* Commented out as it's not working as it should: white before clicking on it, pink if clicking out when the input is invalid. It does turn green when the input is valid, though.
input:invalid {
    background-color: rgba(231, 0, 100);
}

input:valid {
    background-color: rgba(137, 200, 46);

} */

input:required {
    border-color: rgba(60, 60, 59);
}

.grey-mode {
    filter: grayscale(100%);
}

These are my Javascript documents. First, the captcha:

var captcha;
function generate() {
    // Clear old input
    document.getElementById("submit").value = "";
 
        // Access the element to store
        // the generated captcha
        captcha = document.getElementById("image");
        var uniquechar = "";
 
        const randomchar ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
 
        // Generate captcha for length of
        // 5 with random character
        for (let i = 1; i < 5; i++) {
            uniquechar += randomchar.charAt(
                Math.random() * randomchar.length)
        }
 
        // Store generated input
        captcha.innerHTML = uniquechar;
}
 
function printmsg() {
        const usr_input = document
        .getElementById("submit").value;
     
        // Check whether the input is equal
        // to generated captcha or not
        if (usr_input == captcha.innerHTML) {
            var s = document.getElementById("key")
                .innerHTML = "Matched";
            generate();
        }
        else {
            var s = document.getElementById("key")
                .innerHTML = "not Matched";
            generate();
        }
}

The “grey mode”:

function shadesOfGrey() {
  var element = document.body;
  element.classList.toggle("grey-mode");
}

The “pink” out:

// to validate before clicking Submit
function validateName(){
    var name = document.getElementById("nameBox");
    var nameVal = name.value;
    if (!//^([^0-9]*)$/.test(nameVal)){
                name.style.background = #700064;
            
        } else {
                name.style.background = "white";
        }
}

The language-change:

"use strict";
var mlCodes = [
  {
    code: "en",
    name: "English",
  },
  {
    code: "it",
    name: "Italiano",
  },
  {
    code: "es",
    name: "Español",
  },
];

var MLstrings = [
    {
        English: "Validation Page",
        Italiano: "Pagina di Validazione",
        Español: "Página de validación",
    },
    {
        English: "Name",
        Italiano: "Nome",
        Español: "Nombre",
    },
    {
        English: "Email",
        Italiano: "Indirizzo elettronico",
        Español: "Correo electrónico",
    },
    {
        English: "Provider",
        Italiano: "Fornitore",
        Español: "Proveedor",
    },
    {
        English: "Card",
        Italiano: "Carta",

Can’t make a good way to find number of active touch points on the document using a function

I’m trying to get this function to show the number of touchpoints on the screen, but I need it to be instant and accurate. This code works, but when I touch the screen fast it sometimes resolves the “num” variable as 1 when it should be 0. I tried adding a debounce but it still didn’t really fix it. I am new to this so any help is appreciated.

async number() {
  return new Promise((resolve, reject) => {
    let num = 0;
    let timeoutId = null;

    const updateNum = (e) => {
      num = e.touches.length;
      if (timeoutId) {
        clearTimeout(timeoutId);
      }
      timeoutId = setTimeout(() => {
        resolve(num);
        timeoutId = null;
      }, 50);
    };

    document.addEventListener('touchstart', updateNum);
    document.addEventListener('touchend', updateNum);
  });
}

I tried it without the debounce with this code:

async number() {
  return new Promise((resolve, reject) => {
    let num = 0;
    const updateNum = (e) => {
      num = e.touches.length;
      resolve(num);
    };
    document.addEventListener('touchstart', updateNum);
    document.addEventListener('touchend', updateNum);
    document.addEventListener('touchmove', updateNum);
  });
}

But the issue I ran into is that the resolved variable wasn’t accurate when two touch points were added at the exact same time.