Should I use map/reduce/flatten functions to manipulate Multi-Dimensional Array in Javascript

I have this data :

[
["A","X1","Y1"],
["A","X2","Y2"],
["A","X3","Y3"],
["B","X4","Y4"],
["B","X5","Y5"],
["B","X6","Y6"],
]

and would like to change the array structure to be this :

[
["A",["X1","Y1"],["X2","Y2"],["X3","Y3"]],
["B",["X4","Y4"],["X5","Y5"],["X6","Y6"]],
]

I have been playing arund with flatten function (flatten with a ‘key’ (i.e A and B) and then join all back together at the end.) – but the ‘key’ change from A to B (and potentially to C, D, E ….) has got me stumped.

I would appreciate any pointers as to the most efficient direction to go. Has any one else met this type of need ? Is there a better way (outside nested interations)

I am wondering why my for in loop is not looping through my whole object Javascript

I am getting a false Boolean when each object does have name as a property. I consoled the prop var and got 0 back. What am I doing wrong and why is it not looping over every object.

function truthCheck(collection, pre) {

for (let prop in collection){
    console.log(prop)
if(collection[prop].hasOwnProperty(pre) && Boolean(collection.forEach((item)=> item[pre]))){
    
    return true
}
else return false
}
}
console.log(truthCheck([{name: "Quincy", role: "Founder", isBot: false}, {name: "Naomi", role: "", isBot: false}, {name: "Camperbot", role: "Bot", isBot: true}], "name"))

How to return data from InfluxDB observer

Consider the following exerpt from this example in the InfluxDB documentation:

const fluxObserver = {
  next(row, tableMeta) {
    const o = tableMeta.toObject(row)
    console.log(
      `${o._time} ${o._measurement} in ${o.region} (${o.sensor_id}): ${o._field}=${o._value}`
    )
  },
  error(error) {
    console.error(error)
    console.log('nFinished ERROR')
  },
  complete() {
    console.log('nFinished SUCCESS')
  }
}

/** Execute a query and receive line table metadata and rows. */
queryApi.queryRows(fluxQuery, fluxObserver)

The fluxObserver defines a sequence of operations at different stages of execution of the query, all of which are just console.log calls. I can imagine that people want to do something similar in a way that is actually useful, like for instance return an array that contains the result of the query, instead of logging something to a console. My problem is that queryApi.queryRows does not actually return anything, so it is not possible to do something like:

...
  complete() {
    console.log('nFinished SUCCESS')
    return data;
  }
}

/** Execute a query and receive line table metadata and rows. */
var result = queryApi.queryRows(fluxQuery, fluxObserver);
return result;

So how can I return the data collected by the fluxObserver?

Uncaught TypeError: Cannot read properties of undefined (reading ‘param’)

   It's HomePage component of react js 
    import React from 'react';

    import axios from 'axios';
    import {useState, useEffect} from 'react';
    import { useNavigate,useParams } from 'react-router-dom';
    import { Main } from '../components/Main';
    import { Controls } from '../components/Controls';
    import { ALL_COUNTRIES } from '../config';
    import { List } from '../components/List';
    import { Card } from '../components/Card';
    import { Details } from './Details';

    export const HomePage = () => {
     const [countries,setCountries] =useState([]);
     const  navigate  = useNavigate();
     useEffect(()=>{
      axios.get(ALL_COUNTRIES).then(({data})=>setCountries(data))
     },[]);
     return (
       <>
        <Controls/>
      <List>
        {
          countries.map((c)=>
          {
            const countryInfo={
              img:c.flags.png,
              name:c.name,
              info: [
                {
                  title:'Population',
                  description:c.population.toLocaleString(),
                },
                {
                  title:'Region',
                  description:c.region,
                },
                {
                  title:'Flag',
                  description:c.capital,
                },
              ],

            };
            return <Card key={c.name} onClick={(e)=>{navigate('/country/${c.name}')}} 
     {...countryInfo}/>
          })
        }
      </List>
      </>
   );
 };

It’s second components Details

    export const Details = ({match,param,name}) => {
       return (
        <div>
         Details {match.param.name}  
        <div/>
       );
     };

[https://i.stack.imgur.com/KUyrA.png][before]

HomePage itself looks like this
but when i click on flag/card it sends me on second page as expected but gives me this error
[https://i.stack.imgur.com/JqEHm.png][after]

also i’m using react-router-domV6
and this API https://restcountries.com/v2/all
also both Components are in

DOM only first row works perfectly, other row’s doesn’t [duplicate]

I’m working in a form that expands a row after clicking “Add row” button. There are same calculations for each row but only the first row works perfectly. And in the other rows the calculations aren’t working properly and the output in other row’s total price is not being showed and from the second row the values of every input array is being calculated as discount1.Can someone please give the solution. I am posting the table section which is used as a row in the whole container,and my problem is being happened in the table’s row,

function myFunction() {
  var table = document.getElementById("mytable");
  var row = table.insertRow(-1);
  row.innerHTML = '<td><label>Category</label><span>*</span><select class="form-control" id="Category"><option>Select</option><option>A</option><option>B</option><option>C</option><option>D</option></select></td><td><label>Test Name</label><select class="form-control" id="TestName"><option>Select</option><option>A</option> <option>B</option> <option>C</option> <option>D</option> </select></td> <td><label>Price</label> <input type="text" id="Price" name="Price[]" class="form-control" onkeyup="calcAll(this.value);" "></td><td> <label>Discount(%)</label> <div class="row"><div class="col-lg-6"><input type="text" id="Discount1" name="discount1[]" class="form-control" onkeyup="calcAll(this.value);"></div><div class="col-lg-6"><input type="text" id="Discount2" name="discount2[]" class="form-control"></div></div></td><td><label>Total Price</label><input type="text" name="totalPrice[]" id="totalPrice" class="form-control" > </td>  ';


}


function calcAll(value) {

  var discount, y, percent, total;
  y = document.getElementById("Price").value;
  percent = value / 100;
  discount = y * percent;
  document.getElementById("Discount2").value = discount;
  total = y - discount;
  document.getElementById("totalPrice").value = total;


}
<div class="row">
  <table id="mytable">
    <tr>
      <td>
        <label>Category</label>
        <span>*</span>
        <select class="form-control" id="Category">
          <option>Select</option>
          <option>A</option>
          <option>B</option>
          <option>C</option>
          <option>D</option>
        </select>

      </td>


      <td>
        <label>Test Name</label>
        <select class="form-control" id="TestName">
          <option>Select</option>
          <option>A</option>
          <option>B</option>
          <option>C</option>
          <option>D</option>
        </select>

      </td>



      <td>
        <label>Price</label>
        <input type="text" id="Price" name="Price[]" class="form-control" onkeyup="calcAll(this.value);">
      </td>



      <td>
        <label>Discount(%)</label>
        <div class="row">
          <div class="col-lg-6">
            <input type="text" id="Discount1" name="discount1[]" class="form-control" onkeyup="calcAll(this.value);">
          </div>

          <div class="col-lg-6">
            <input type="text" id="Discount2" name="discount2[]" class="form-control">
          </div>
        </div>

      </td>

      <td>
        <label>Total Price</label>
        <input type="text" name="totalPrice[]" id="totalPrice" class="form-control">

      </td>



    </tr>

  </table>


</div>

<button type="button" onclick="myFunction()">Add rows</button>

How to make ajax call simultaneously Without waiting for the one ajax call to finis in onclick event

<html>
<head></head>
<body>
<button onclick="ajaxcall()">Call the function</button>
</body>
<script>
function ajaxcall()
{
      $.ajax({
                     url: 'insertdata.php',
                     data: {
                        userdata:userdata
                            },
                     type: 'POST',
                     success: function(response) {
     //I have been using the response
                                                }
                          });
}
</script>
</html>

insertdata.php

<?php
$userdata = $_POST["userdata"];
// I have been getting userdata from ajax using post method

// Then I inserting to my aws database using api and it will take 2 to 5 seconds to get response from the api

?>

Description

  1. From the html code you can see that when I click the button, I have been calling “ajax” and sending the data to the “insertdata.php” and insert the data into the database inside “insertdata.php” file using “api”

  2. When I click the button it’s calling the ajax and wait for the response for 2 seconds.

  3. After I click the button simultaneously The ajax is running one by one so it’s taking too long to finis the process

  4. What I need is when I click the button second time, It should run Parallel with the first ajax call instead of waiting to finish the first ajax call.

Example

1.When I click the button for 5 times it takes 2 second to finish the ajax call so it’s totally taking time 10 seconds.

  1. I need the 5 ajax call to run parallelly Without waiting for one ajax call to finish to start another ajax

You can also suggest alternative for ajax

Uncaught ReferenceError: praseFloat is not defined

The code can’t find the class from another variable in javascript (at cartRows = cartItemContainer).

    var cartItemContainer = document.getElementsByClassName('cart-items')[0]
    var cartRows = cartItemContainer.getElementsByClassName('cart-row')

All javascript code

console.log(removeCartItemButtons)
for (var i = 0; i < removeCartItemButtons.length; i++) {
    var button = removeCartItemButtons[i]
    button.addEventListener('click', function(event) {
        var buttonClicked = event.target
        buttonClicked.parentElement.parentElement.parentElement.remove()
        updateCartTotal()
    })
}

function updateCartTotal() {
    var cartItemContainer = document.getElementsByClassName('cart-items')[0]
    var cartRows = cartItemContainer.getElementsByClassName('cart-row')
    for (var i = 0; i < cartRows.length; i++) {
        var cartRow = cartRows[i]
        var priceElement = cartRow.getElementsByClassName('cart-price')[0]
        var quantityElement = cartRow.getElementsByClassName('cart-quantity-items')[0]
        var price = parseFloat(priceElement.innerText.replace('lei', ''))
        console.log(price)
    }
}

html code

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title>Title</title>

    <link href="assets/css/style.css" rel="stylesheet" />
    <script src="cart.js" async></script>
</head>
.
.
.
.
.

                    <tbody class="cart-items">
                      <div class="cart-row">
                        <tr>
                          <td class="indecor-product-remove">
                            <a href="#/"><i class="fa fa-times btn-remove"></i></a>
                          </td>
                          <td class="indecor-product-thumbnail">
                            <a href="#/"><img src="assets/img/shop/cart/table1.jpg" alt="Image-HasTech"></a>
                          </td>
                          <td class="indecor-product-name">
                            <h4 class="title"><a href="single-product.html">Meta Slevless Dresss</a></h4>
                          </td>
                          <td class="indecor-product-price"><span class="price cart-price">70.00 lei</span></td>
                          <td class="indecor-product-quantity">
                            <div class="pro-qty">
                              <input type="text" class="cart-quantity-items" id="quantity" title="Quantity" value="1">
                            </div>
                          </td>
                          <td class="product-subtotal"><span class="price">70.00 lei</span></td>
                        </tr>
                      </div>
                      <div class="cart-row">
                        <tr>
                          <td class="indecor-product-remove">
                            <a href="#/"><i class="fa fa-times btn-remove"></i></a>
                          </td>
                          <td class="indecor-product-thumbnail">
                            <a href="#/"><img src="assets/img/shop/cart/table2.jpg" alt="Image-HasTech"></a>
                          </td>
                          <td class="indecor-product-name">
                            <h4 class="title"><a href="single-product.html">Literature Classicals</a></h4>
                          </td>
                          <td class="indecor-product-price"><span class="price cart-price">79.00 lei</span></td>
                          <td class="indecor-product-quantity">
                            <div class="pro-qty">
                              <input class="cart-quantity-items" type="text" id="quantity" title="Quantity" value="1">
                            </div>
                          </td>
                          <td class="product-subtotal"><span class="price">79.00 lei </span></td>
                        </tr>
                      </div>
                    </tbody>
    

I am confused with async-await

My code should wait for 4-4 seconds for both the promise to execute total 8 seconds, but it is finishing in 4 seconds only. Why?
Where I am thinking wrong?

// a promise
let promise1 = new Promise(function (resolve, reject) {

    setTimeout(function () {
    resolve('Promise resolved1')}, 4000); 
});
let promise2 = new Promise(function (resolve, reject) {

    setTimeout(function () {
    resolve('Promise resolved2')}, 4000); 
});


// async function
async function asyncFunc() {

    // wait until the promise resolves 
    let result1 = await promise1; 
    let result2 = await promise2; 
    console.log(result1);
    console.log(result2);

}

// calling the async function
asyncFunc();
//expected output

**//wait for 4 seconds first**
Promise resolved1 
**//wait for more 4 seconds**
Promise resolved2

//output
//waits for 4 seconds
Promise resolved1
Promise resolved2

How to create a slide out animated hamburger menu

This is my code,
index.html:-

<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
  <title>Cool Navbar</title>
</head>
<body>
    <header class="pc-nav">
        <div class="container">
            <h1>Saroni Global</h1>

            <div class="menu">
                <a href="" class="is-active">Home</a>
                <a href="">About</a>
                <a href="">Products</a>
                <a href="">Contact</a>
            </div>

            <button class="hamburger">
                <span></span>
                <span></span>
                <span></span>
            </button>
        </div>
    </header>
    <nav class="mobile-nav">
        <a href="">Home</a>
        <a href="">About</a>
        <a href="">Products</a>
        <a href="">Contact</a>
    </nav>
    <script src="main.js"></script>
</body>
</html>

style.sass code:-

$primary: #8c38ff
$light: #eeeeee
$dark: #212121

* 
    margin: 0
    padding: 0
    box-sizing: border-box
    font-family: 'Fira sans', sans-serif

.container
    max-width: 1280px
    margin: 0 auto
    
    display: flex
    align-items: center
    justify-content: space-between

header
    position: fixed
    left: 0
    right: 0
    z-index: 99    
    background-color: $dark
    padding: 16px 32px
    border-bottom: 3px solid $primary

h1
    color: #FFF
    font-size: 26px
    font-weight: 900
    letter-spacing: 1px
    text-transform: uppercase

.hamburger
    display: block
    position: relative
    z-index: 1

    user-select: none

    appearance: none
    border: none
    outline: none
    background: none
    cursor: pointer
    span
        display: block
        width: 33px
        height: 4px
        margin-bottom: 5px
        position: 
        
        background-color: $light
        border-radius: 6px
        z-index: 1

        transform-origin: 0 0

        transition: 0.4s
    

.hamburger:hover
    span:nth-child(2)
        transform: translateX(10px)
        background-color: $primary
.is-active
    span:nth-child(1)
        transform: translate(0px, -2px) rotate(45deg)
    span:nth-child(2)
        opacity: 0
        transform: translateX(15px)
    span:nth-child(3)
        transform: translate(-3px, 3px) rotate(-45deg)
.is-active:hover
    span
        background-color: $primary

.menu
    display: none
    flex: 1 1 0%
    justify-content: flex-end
    margin: 0 -16px
    a
        color: #FFF
        margin: 0 16px
        font-weight: 600
        text-decoration: none
        transition: 0.4s
        padding: 8px 16px
        border-radius: 19px
    a
    .is-active
        background-color: $primary
    a:hover
        background-color: $primary



@media (min-width: 768px) 
    .hamburger
        display: none
    .menu
        display: flex

My javascript doesn’t contain much it just adds an class to my hamburger menu icon to animate the when clicked, but I wanted to know how to create an animated hamburger slider. How can I do it, btw for whom who doesn’t know sass is it’s just a sassy version of css

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Fira sans', sans-serif;
}

.container {
  max-width: 1280px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

header {
  position: fixed;
  left: 0;
  right: 0;
  z-index: 99;
  background-color: #212121;
  padding: 16px 32px;
  border-bottom: 3px solid #8c38ff;
}

h1 {
  color: #FFF;
  font-size: 26px;
  font-weight: 900;
  letter-spacing: 1px;
  text-transform: uppercase;
}

.hamburger {
  display: block;
  position: relative;
  z-index: 1;
  user-select: none;
  appearance: none;
  border: none;
  outline: none;
  background: none;
  cursor: pointer;
}

.hamburger span {
  display: block;
  width: 33px;
  height: 4px;
  margin-bottom: 5px;
  background-color: #eeeeee;
  border-radius: 6px;
  z-index: 1;
  transform-origin: 0 0;
  transition: 0.4s;
}

.hamburger:hover span:nth-child(2) {
  transform: translateX(10px);
  background-color: #8c38ff;
}

.is-active span:nth-child(1) {
  transform: translate(0px, -2px) rotate(45deg);
}

.is-active span:nth-child(2) {
  opacity: 0;
  transform: translateX(15px);
}

.is-active span:nth-child(3) {
  transform: translate(-3px, 3px) rotate(-45deg);
}

.is-active:hover span {
  background-color: #8c38ff;
}

.menu {
  display: none;
  flex: 1 1 0%;
  justify-content: flex-end;
  margin: 0 -16px;
}

.menu a {
  color: #FFF;
  margin: 0 16px;
  font-weight: 600;
  text-decoration: none;
  transition: 0.4s;
  padding: 8px 16px;
  border-radius: 19px;
}

.menu .is-active {
  background-color: #8c38ff;
}

.menu a:hover {
  background-color: #8c38ff;
}

@media (min-width: 768px) {
  .hamburger {
    display: none;
  }
  .menu {
    display: flex;
  }
}
<!doctype html>
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
  <title>Cool Navbar</title>
</head>

<body>
  <header class="pc-nav">
    <div class="container">
      <h1>Saroni Global</h1>

      <div class="menu">
        <a href="" class="is-active">Home</a>
        <a href="">About</a>
        <a href="">Products</a>
        <a href="">Contact</a>
      </div>

      <button class="hamburger">
                <span></span>
                <span></span>
                <span></span>
            </button>
    </div>
  </header>
  <nav class="mobile-nav">
    <a href="">Home</a>
    <a href="">About</a>
    <a href="">Products</a>
    <a href="">Contact</a>
  </nav>
  <script src="main.js"></script>
</body>

</html>

How to get all records, where the date value in the record is older then an hour with Prisma DB and javascript?

This is what I am doing right now:

const addHours = function (date: Date, hours: number) {
  date.setTime(date.getTime() + (hours * 60 * 60 * 1000))
  return date;
}
let expiredReservation = await prisma.collectionIndexes.findMany({
    where: {
        AND: [
            {
                collectionId: dbCollection.id
            },
            {
                submitedTx: null
            }
        ]
    },
    orderBy: {
        reservedAt: 'asc'
    }
})
expiredReservation = expiredReservation.filter(r => addHours(r.reservedAt, 1).getTime() < new Date().getTime())

These are my models:

model CollectionIndexes {
  id            Int        @id @unique @default(autoincrement())
  submitedTx    String?

  collection    Collection @relation(fields: [collectionId], references: [id])
  collectionId  Int

  reservedIndex Int
  reservedAt    DateTime   @default(now())

}

model Collection {
  id                Int                 @id @unique @default(autoincrement())
  collectionName    String              @unique
  collectionLimit   Int?
  CollectionIndexes CollectionIndexes[]
}

I would much rather just get the correct records from prisma db, without doing filter after. If it’s possible, how to write it?

How to dynamically highlight changing numbers?

I have been searching for days now.

I have some random numbers that are generated automatically with crunch function on 3 minute interval:

setInterval(crunch, 180000);

then I can nicely highlight the return random numbers with mark.js:

$(function() {
        var mark = function() {
            // Read the keyword
            var keyword = $("input[name='keyword']").val();
            var keyword2 = $("input[name='keyword2']").val();
            // Remove previous marked elements and mark
            // the new keyword inside the context
            $(".context").unmark({
                done: function() {
                    $(".context").mark(keyword).mark(keyword2, {
                        className: 'secondary'
                    });
                }
            });
        };
        $("input[name^='keyword']").on("input", mark);
    });

My problem is when the second lot of new numbers are generated the highlight goes away – please can you kindly share a way how I can make them stay highlighted forever?

Here is my working fiddle on a 3 min interval:

https://jsfiddle.net/heybubbles/eztgy7j9/12/

min: 1
max: 100
results: 100

I tend to search for the highlighted number after generation not sure how to make
it search on generation apologies.

Many thanks in advance!

I can’t link to a new page with active class by JavaScript on PHP

Every one.

I’m a new learner on PHP. I can’t solve any problem on my code.

In sidebar.php

<nav class="side-bar">
        <ul>
            <li>
                <a href="index.php" class="category active">
                    <i class="fi fi-bs-home"></i>
                    <span>Home</span>
                </a>
            </li>
            <li>
                <a href="#" class="category">
                    <i class="fi fi-bs-apps"></i>
                    <span>Room</span>
                </a>
            </li>
            <li>
                <a href="contact.php" class="category">
                    <i class="fi fi-br-comment-alt"></i>
                    <span>Contact</span>
                </a>
            </li>
            </ul>
</nav>

In script.js

const category = document.querySelectorAll('.category');

category.forEach(cate =>{
    cate.addEventListener('click',()=>{
        removeClass();
        cate.classList.add('active');
    })
})

function removeClass(){
    category.forEach(cate=>{
        cate.classList.remove('active');
    })
}

In index.php

#code
<?php include ("sidebar.php"); ?>
#code

but active class not working when I link to a new page. but it work if I use href=”#” in tag. How can I solve this problem?

Clean Up code not works correctly in React when using AbortController

I’m using a Custom useHttp hook to fetch some data from api , the problem is that i want to abort fetching operation when user navigates to another page and prevent weird errors .
for this I’m using AbortController API inside my hook and whenever the component unmounts the function will be fired .
but when my component renders , i will get an error that telling me the operation was aborted !

Hook Code :

import { useEffect , useState , useCallback , useRef } from 'react';

export const useHttpClient = () => {
   const [isLoading, setIsLoading] = useState(false);
   const [error, setError] = useState();


   const activeHttpRequests = useRef([]);

   const sendRequest = useCallback(async (URL, method = 'GET', body = null, headers = {}) => {
      setIsLoading(true);


      
      const httpAbortController = new AbortController();
      activeHttpRequests.current.push(httpAbortController);

      try {
         const res = await fetch(URL, {method, body, headers, signal: httpAbortController.signal});
         const resData = await res.json();
         
         activeHttpRequests.current = activeHttpRequests.current.filter(reqCtrl => reqCtrl !== httpAbortController)
         console.log(activeHttpRequests)
         
         if(!res.ok) {
            throw new Error(resData.error);
         }
         setIsLoading(false)   
         return resData;
      } catch (error) {
         setIsLoading(false)   
         setError(error.message)
         throw error;
      }
   }, [])

   const clearError = () => {
      setError(null);
   }


   useEffect(() => {
      return () => {
         activeHttpRequests.current.forEach(abortCtrl => abortCtrl.abort());
      };
   }, []);

   return {isLoading, error, clearError, sendRequest}
}

and this is the code inside my component :

// Modules
import React, { useEffect, useState } from 'react';

// Hooks 
import { useHttpClient } from '../../../helpers/hooks/http-hook';

// Components
import UserList from '../components/user-list/user-list.component';
import ErrorModal from '../../shared/error-modal/error-modal.component';
import Spinner from '../../shared/loading-spinner/spinner.component';


const Users = () => {
   const { isLoading , error , clearError , sendRequest } = useHttpClient();
   const [loadedUsers, setLoadedUsers] = useState();
   
   useEffect(() => {
      const fetchUsers = async () => {
         try {
            const URL = 'http://localhost:5000/api/users';
            const res = await sendRequest(URL);
            setLoadedUsers(res.users);
         } catch (error) {}
      }
      fetchUsers();
   }, [sendRequest])


   return (
      <React.Fragment>
         <ErrorModal error={error} onClear={clearError} />
         { isLoading && <Spinner overlay/> }
         { !isLoading && loadedUsers && <UserList users={loadedUsers} /> }
      </React.Fragment> 
   );
}
export default Users;

How to change root element with another root element property on js

hello guys i have a little problem but i cant figure out can you help me?
I have a some code in css

/* Colors        */
--white:#fff;
--dark:#000;
--purple:#9051ff;
--crimson:crimson;
--black:#0c192c;
/* Font Sizes*/
--onpxfont:10px;
--onikipxfont:12px;
--ondortpxfont:14px;
--onaltipxfont:16px;
--currentfont: var(--onikipxfont);
} 

html too like that;

   <div class="container">
       <section id="home">
           <div  id="ct" class="customize-theme">
               <h3>Font Büyüklüğü</h3>
               <ul>
                   <li id="on"><img   src="./font.png">10px</li>
                   <li id="oniki" class="oniki active"><img  src="./font.png">12px</li>
                   <li id="ondort"><img  src="./font.png">14px</li>
                   <li id="onalti"><img src="./font.png">16px</li>
               </ul>
                <h3>Tema Rengi</h3>
                <div class="renkler">
                   <span id="red"></span>
                   <span id="black"></span>
                   <span id="purple"></span>
                   <span id="orange"></span>
                </div>
                
           </div>

and lastly my js like that;

<script>
   const settings = document.getElementById('settings');
   const customizetheme = document.getElementById('ct');
   let onpx = document.getElementById('on');
   let onikipx = document.getElementById('oniki');
   let ondortpx = document.getElementById('ondort');
   let onaltipx = document.getElementById('onalti');
   let changeforred = document.getElementById('red');
   let changeforblack = document.getElementById('black');
   let changeforpurple = document.getElementById('purple');
   let changefororange = document.getElementById('orange');


   onpx.onclick = function () {
       document.documentElement.style.setProperty('--currentfont', '10px');
       onpx.classList.add('active'),
       onikipx.classList.remove('active'),
       ondortpx.classList.remove('active'),
       onaltipx.classList.remove('active');

   }

 onikipx.onclick = function () {
   document.documentElement.style.setProperty('--currentfont', '12px');
       onpx.classList.remove('active'),
       onikipx.classList.add('active'),
       ondortpx.classList.remove('active'),
       onaltipx.classList.remove('active');

   }
   ondortpx.onclick = function () {
       document.documentElement.style.setProperty('--currentfont', '14px');
       onpx.classList.remove('active'),
       onikipx.classList.remove('active'),
       ondortpx.classList.add('active'),
       onaltipx.classList.remove('active');

   }
   onaltipx.onclick = function () {
       onpx.classList.remove('active'),
       onikipx.classList.remove('active'),
       ondortpx.classList.remove('active'),
       onaltipx.classList.add('active');
       document.documentElement.style.setProperty('--currentfont', '16px');
   }

</script>

but when i want change code like that… my code broken what’s the wrong can you explaing me?

<script>
   const settings = document.getElementById('settings');
   const customizetheme = document.getElementById('ct');
   let onpx = document.getElementById('on');
   let onikipx = document.getElementById('oniki');
   let ondortpx = document.getElementById('ondort');
   let onaltipx = document.getElementById('onalti');
   let changeforred = document.getElementById('red');
   let changeforblack = document.getElementById('black');
   let changeforpurple = document.getElementById('purple');
   let changefororange = document.getElementById('orange');


   onpx.onclick = function () {
       document.documentElement.style.setProperty('--currentfont', 'onpxfont');
       onpx.classList.add('active'),
       onikipx.classList.remove('active'),
       ondortpx.classList.remove('active'),
       onaltipx.classList.remove('active');

   }

 onikipx.onclick = function () {
   document.documentElement.style.setProperty('--currentfont', 'onikipxfont');
       onpx.classList.remove('active'),
       onikipx.classList.add('active'),
       ondortpx.classList.remove('active'),
       onaltipx.classList.remove('active');

   }
   ondortpx.onclick = function () {
       document.documentElement.style.setProperty('--currentfont', 'ondortpxfont');
       onpx.classList.remove('active'),
       onikipx.classList.remove('active'),
       ondortpx.classList.add('active'),
       onaltipx.classList.remove('active');

   }
   onaltipx.onclick = function () {
       onpx.classList.remove('active'),
       onikipx.classList.remove('active'),
       ondortpx.classList.remove('active'),
       onaltipx.classList.add('active');
       document.documentElement.style.setProperty('--currentfont', 'onaltipxfont');
   }

</script>

Frankly, I think we can’t change var with set property, I don’t know, I have no idea.