Can some one tell me why I cannot get the date

When trying to make a date variable in JS and console.log(ing) it returns Invalid date, am I being stupid can someone help me.

let yr = String(new Date().getFullYear());
let mnth = new Date();
mnth = String(getMonthShortName(new Date().getMonth()));
let dte = String(new Date().getDate());
let hr = String(new Date().getHours());
let min = String(new Date().getMinutes());
let sec = String(new Date().getSeconds());
date2 = new Date(String(mnth + " " + dte + " " + yr + " " + hr + " " + min + " " + sec));
console.log("Date (full): " + date2);

function getMonthShortName(monthNo) {
  const date = new Date();
  date.setMonth(monthNo - 1);
  return date.toLocaleString('en-US', {
    month: 'short'
  });
}

Creating system mode mode (dark mode)

I am going to design a dark mode for my wordpress theme.

I have no problem designing dark mode and light mode and I have easily designed these two.
But I’m looking to create a third mode which is the default for pages.

The third mode I want to create is the automatic use of dark mode or light mode using the user’s default settings for their browser or system.

Something similar to the site (stackoverflow.com) that I have placed in the image below:

enter image description here

I don’t know where to start to create such a state and all the code I wrote is as follows:

let bodyMode = document.querySelector("#pageMode");
let SystemMode = document.querySelector(".SystemMode");
let DarkMode = document.querySelector(".DarkMode");
let LightMode = document.querySelector(".LightMode");

SystemMode.addEventListener("click", function () {

//I don't have any idea to create mod system mode

});

DarkMode.addEventListener("click", function () {
    $(bodyMode).addClass("bodyDark");
    $(bodyMode).removeClass("bodyHalfLit");
});

LightMode.addEventListener("click", function () {
    $(bodyMode).removeClass("bodyDark");
    $(bodyMode).removeClass("bodyHalfLit");
});
#pageMode {
  background: #eee;
}

.bodyDark {
  background: #000 !important;
}

.bodyHalfLit {
  background: #909090 !important;
}

.main-selectMode {
  position: absolute;
  top: 20%;
  left: 2%;
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>



<body id="pageMode">

    <div class="dropdown main-selectMode">
        <a class="btn btn-secondary dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown"
            aria-expanded="false">
            page Mode
        </a>

        <ul class="dropdown-menu">
            <li class="SystemMode"><a class="dropdown-item">System Mode</a></li>
            <li class="LightMode"><a class="dropdown-item">Light Mode</a></li>
            <li class="DarkMode"><a class="dropdown-item">Dark Mode</a></li>
        </ul>
    </div>


</body>

Rotation using Panolens causes panorama image issues

Im currently trying to create a website where you can switch between two panorama images with a button click. Im using Panolens and their viewer. I want to make sure the rotation of the two images are aligned so when i switch between the two I will see how its different. For context, its our home before and after renovations.

The photos seem to cause some issues when trying to rotate the photos. They load and there are some black spots on the photo, and then they disappear. I have a photo of what happens. Result of rotation

For reference, this is some of code for the panoramas I have on the website, including the rotations adjustment:

//Starting rotations for second images
    const rotations = [0,-Math.PI/4,0,0,0,0,0,0,0];

    //Adding the panoramas to their viewer
    for (let i = 0; i < viewers.length; i++) {
        images[i][1].rotation.y = rotations[i]; //Adding rotations
        viewers[i].OrbitControls.noZoom = true; //Remove zoom from them
        viewers[i].add(images[i][0])
        viewers[i].add(images[i][1])
    }

I have multiple panorama viewers and images, and its only the rotation that causes issues

I have tried using yaw and pitch, the rotation component and other ways. But if there isn’t a way to fix this, no worries.

Thanks

How to access a cookie created via Sveltkit cookies from axios interceptor

I’ve got a Login form with the following action (login/+page.server.js):

export const actions = {

    default: async ({ request, cookies }) => {

        const data = Object.fromEntries(await request.formData());
        
        // validate and create DTO.
        const loginData = loginDTO(data);

        // if errors returned from building the DTO (validation errors) then return the object.
        if (loginData?.errors && !emptyObject(loginData.errors)) {
            return {
                "data": loginData.data,
                "errors": loginData.errors,
            };
        }


        // perform call to log in a user.
        const response = await login(loginData);
        // const response = await loginUser(loginData);
        if (response.success) {
            // save token to a cookie
            cookies.set(
                'token',
                response.res.data.data,
                {
                    path: '/',
                    maxAge: 60 * 60 * 25 * 365,
                    httpOnly: false,
                    secure: false,
                }
            )

            throw redirect(302, '/')
        }

        return {
            "data": loginData.data,
            "errors": response.errors,
        }
    }
}

basically this is making a request to the backend authenticating a user an a JWT token is returned. So far so good, the token is returned and using Sveltekit’s cookies I can successfully set the cookie, when I inspect Chrome’s application tab (in dev tools) I can see the cookie there.

dev tools img

Now, I need to attach the value of the cookie to my requests. I’m using axios. To do so I created an interceptor:

import axios from "axios";
import Cookies from "js-cookie";

// let Cookies2 = Cookies.noConflict();
export const app = axios.create({
    baseURL: "http://127.0.0.1:8080/api/v1",
    timeout: 1000,
    params: {},
    // withCredentials: true,
})
// Request interceptor. Whenever a new request goes out it will be caught
// by the interceptor and whatever code is defined will be executed before continuing its flow.
app.interceptors.request.use(
    config => {
        
        console.log("here in http middleware...")
        let token = Cookies.get()
        console.log("token: ", token);
        config.headers['Content-Type'] = 'application/json';
        return config;
    },
    error => {
        Promise.reject(error)
    }
);

But I’ve got a couple issues:

  1. I haven’t been able to use Sveltekit’s cookies object, don’t know how to import it here.
  2. Since the cookie is visible client-side, I decided to install js-cookie to access it, but the log statement I’ve got in the interceptor is always coming back empty, meaning that it’s not picking up the cookie.

Any idea what’s going on? or any other way I can achieve what I’m trying to do?

I could also scrap the whole cookies approach and simply use a store, what are the cons and pros of each approach?

Thanks.

Vue js component is not working properly when reused in the same page

I have 2 components, parent and child. The child component fetches data to be shown based on the props that are passed into it. It works fine when I have one child component on a page, but when I try to use 2 of them(with different filters) only the last one contains items. What am I doing wrong?

Here are the simplified examples of both components

Parent component

    <main>
        <div class="container mx-auto sm:px-6 lg:px-8">
            <ItemList listName="listWith10Items" limit="10"></ItemList>
            <ItemList listName="listWith20Items" limit="20"></ItemList>
        </div>
    </main>

Child component

<template>
  <div>
    <h2 class="text-2xl font-extrabold tracking-tight text-gray-900">{{ listName }}</h2>

    <ul role="list" class="mx-4 inline-flex space-x-8 sm:mx-6 no-scrollbar">
      <li v-for="item in items" :key="item.id" class="w-64 inline-flex flex-col text-center">
        <span>{{item.title}}</span>
      </li>
    </ul>
  </div>
</template>

<script>

export default {
  props: {
    listName: String,
    limit: Number,
  },
  data() {
    return {
      items: []
    }
  },
  created() {
    self = this;
    axios.get('***?limit=' + this.limit).then(res => self.items = res.data);
  }
}
</script>

How to uncheck all other radio buttons when one is checked

I customized te radio button of bootstrap. Now I am unable to select the radio button i.e. the radio button won’t remain checked. I want the radio buttons to remain checked or I want to be able to select. And I also want to uncheck all other radio buttons once another radio button is selected. How can i do this in javascript. Here is my code of the custom design of the radio button:

HTML:

`<div class="row">
    <div class="col-lg-12 col-md-12 col-12">
        <p class="form-label px-1 mt-3 col-12">Gender</p>                                
    </div>

    <div class="col-lg-6 col-12 gender-div d-flex">
        <div class="col-6 gender-radio-div">
            <p id="gender-male-fake-sibling" class="d-none">dfs</p>
            <label for="gender" class="gender-label" id="frist-label">
                <!-- <input type="radio" name="gender" id="male" class="gender-radio" value="Male"> -->
                <input type="radio" name="gender" id="male" class="gender-radio" value="Male" data-gender="Male">
                <span class="gender-span">Male</span>
            </label>
        </div>
        <div class="col-6 gender-radio-div">
            <p id="gender-male-fake-sibling" class="d-none">dfs</p>
            <label for="gender" class="gender-label">
                <!-- <input type="radio" name="gender" id="female" class="gender-radio" value="Female"> -->
                <input type="radio" name="gender" id="female" class="gender-radio" value="Female" data-gender="Female">
                <span class="gender-span">Female</span>
            </label>
            {% comment %} <input class="form-check-input" type="checkbox" value="">
            <label class="form-check-label" for="flexCheckChecked">Female</label> {% endcomment %}
        </div>
        
    </div>
</div>`

CSS:

.gender-label {
    height: 20px;
    width: 20px;
    vertical-align: middle;
    margin-right: 5px;
    border: 1px solid rgb(235, 164, 117);
    border-radius: 50%;
    text-align: center;
    transition: 0.3s;
}

.gender-label:hover {
    border-color: rgb(255, 108, 50);
    background-color: rgb(255, 108, 50);
    color: rgb(0, 0, 0);
    cursor: pointer;
}

.gender-div input{
    display: none;
}

.gender-radio-div{
    position: relative;
}

.gender-radio-div .gender-span{
    position: absolute;
    left: 35px;
    top: 2px;
}

Javascript:

`<script type="text/javascript">
    var radioInputs = document.querySelectorAll('input[type="radio"][name="gender"]');

    radioInputs.forEach(function(input) {
        input.addEventListener('click', function() {

            var clickedName = this.name;
            // uncheck all other radio buttons
            radioInputs.forEach(function(radioInput) {
                if (radioInput.name == clickedName && radioInput != input) {
                    radioInput.checked = false;
                }
            })

            // check the clicked radio button
            this.checked = true;
        });
    });

</script>`

I was expecting that when I select one radio button it should uncheck all other radio buttons. I was hoping if anyone could help me do this using javascript. Please review my code and give feedback.
Thank You

String hashed with Bcrypt returns ‘undefined’ in object list

I have this code to hash strings and put them in an object list. The hashed strings say ‘undefined’ in the terminal when I print the object list. When I print the hash from the function, it clearly shows the hash.

What am I missing here?

const bcrypt = require('bcrypt')

const users = []

function hashPassword(password, salt) {
    bcrypt
    .hash(password, salt)
    .then(hash => {
        console.log(hash)
        return hash
    })
    .catch(err => console.log(err.message))
}

const hashedPassword = hashPassword('asdasdasd', 10)

users.push({
    "ID": 01,
    "Name": "Ali Haider",
    "Email": "[email protected]",
    "Password": hashedPassword
})

users.push({
    "ID": 02,
    "Name": "Kumai",
    "Email": "[email protected]",
    "Password": hashedPassword
})

console.log(users)

Here’s the result when I run the code:

PS D:_Programmingjs> node app.js
[
  {
    ID: 1,
    Name: 'Ali Haider',
    Email: '[email protected]',
    Password: undefined
  },
  {
    ID: 2,
    Name: 'Kumai',
    Email: '[email protected]',
    Password: undefined
  }
]
JSON file created.
$2b$10$qEap/oHdL4hrRN9T6Ahr2eZyoIu96Q.23qiHFa0eD1DeN65OhZQB2

Local debug Webpack application

When I run webpack serve --port 8080 --open --config webpack.dev.js --static-directory www, it serves the files from www at https://localhost:8080. However, it does not build the entry-point JavaScript. Why?

I’m having to explicitly run webpack -c webpack.dev.js before webpack serve. Is there a way to run it in parallel with webpack serve while also watching for changes?

webpack.common.js:

const path = require('path');

module.exports = {
  entry: './src/main.ts',
  output: {
    path: path.resolve(__dirname, 'www/res/js/build'),
    publicPath: path.resolve(__dirname, 'www/res/js/build'),
    filename: 'main.js',
  },
  // ...
}

How can I use “First Name” entered by user and use it as personalisation in a multi-step form questions?

This is a simple HTML structure of a multi-step form. I want to use the first name of user as personalisation in form section <p>.

For say if some one enter his name as “Jack” and then clicks on next button…. then in the next section the <p> will read as “Jack, What’s your age?” and then the final section’s <p> will be “Are you good Jack?”

<form action="">
            <div class="section1">
                <input type="text" placeholder="First Name">
                <button class="next-btn">Next</button>
            </div>
            <br>
            <div class="section2">
                <p>[First Name], What's your age?</p>
                <input type="number" class="age" placeholder="Your Age" >
                <button class="next-btn">Next</button>
            </div>
            <br>
            <div class="section3">
                <p>Are you doing good [First Name]?</p>
                <input type="text" class="good" placeholder="Yes or No ?" >
                <button class="submit">submit</button>
            </div>
        </form>

I am new to JS. So am not able to understand that how to do this. Looking forward to some assistance please.

PayPal React Js buttons sometimes disappear

I am building a basic react integration, and I tested that buttons do work properly, except that about half of the time, they just simply disappear from the webpage after appearing briefly for 100ms or so

import React from 'react';
import "./website1.css"
//import { loadScript } from 'paypal-checkout';
import { PayPalScriptProvider, PayPalButtons, usePayPalScriptReducer } from "@paypal/react-paypal-js";
import { useEffect } from "react";


class Website1 extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      cartItems: []
    };
    this.addToCart = this.addToCart.bind(this);
    this.removeFromCart = this.removeFromCart.bind(this);
    this.handleEmptyCart = this.handleEmptyCart.bind(this);
  }


  addToCart(item) {
    this.setState(prevState => ({
      cartItems: [...prevState.cartItems, item]
    }));
  }

  handleEmptyCart() {
    this.setState({ cartItems: [] });
  }


  removeFromCart(index) {
    this.setState(prevState => {
      const newItems = [...prevState.cartItems];
      newItems.splice(index, 1);
      return { cartItems: newItems };
    });
  }

  render() {
    return (
      <div className="website1-container">
        <div className="products-container">
          <h2>Products</h2>
          <ul>
            <li>
              Product 1
              <button onClick={() => this.addToCart("Product 1")}>
                Add to cart
              </button>
            </li>
            <li>
              Product 2
              <button onClick={() => this.addToCart("Product 2")}>
                Add to cart
              </button>
            </li>
            <li>
              Product 3
              <button onClick={() => this.addToCart("Product 3")}>
                Add to cart
              </button>
            </li>
          </ul>
        </div>
        <div className="cart-panel">
          <h2>Shopping Cart</h2>
          <ul>
            {this.state.cartItems.map((item, index) => (
              <li key={index}>
                {item}
                <button onClick={() => this.removeFromCart(index)}>
                  Remove
                </button>
              </li>
            ))}
            {/* Check if the cart is not empty */}
            {this.state.cartItems.length > 0 && (
              <><button className="empty-cart-button" onClick={this.handleEmptyCart}>Empty Cart</button><div className="paypal-buttons-container" id="paypal-button-container">
                <PayPalScriptProvider
                  options={{
                    "client-id": "myid",
                    components: "buttons",
                    currency: "USD"
                  }}
                >
                  <ButtonWrapper
                    currency={currency}
                    showSpinner={true}
                  >
                  </ButtonWrapper>
                </PayPalScriptProvider>

              </div></>
            )}
          </ul>
        </div>
      </div>
    );
  }

}

export default Website1;
// This values are the props in the UI
const amount = "2";
const currency = "USD";
const style = { "layout": "vertical" };

// Custom component to wrap the PayPalButtons and handle currency changes
const ButtonWrapper = ({ currency, showSpinner }) => {
  // usePayPalScriptReducer can be use only inside children of PayPalScriptProviders
  // This is the main reason to wrap the PayPalButtons in a new component
  const [{ options, isPending }, dispatch] = usePayPalScriptReducer();

  useEffect(() => {
    dispatch({
      type: "resetOptions",
      value: {
        ...options,
        currency: currency,
      },
    });
  }, [currency, showSpinner]);


  return (<>
    {(showSpinner && isPending) && <div className="spinner"></div>}
    <p>Buttons go here</p>
    <PayPalButtons
      style={style}
      disabled={false}
      forceReRender={[amount, currency, style]}
      fundingSource={undefined}
      createOrder={(data, actions) => {
        return actions.order
          .create({
            purchase_units: [
              {
                amount: {
                  currency_code: currency,
                  value: amount,
                },
              },
            ],
          })
          .then((orderId) => {
            // Your code here after create the order
            return orderId;
          });
      }}
      onApprove={function (data, actions) {
        return actions.order.capture().then(function () {
          // Your code here after capture the order
        });
      }}
    />
  </>
  );
}

The backend works fine as far as I know

It’s using the server.js from standard-integration

import "dotenv/config"; // loads variables from .env file
import express from "express";
import * as paypal from "./paypal-api.js";
const { PORT = 3000 } = process.env;

const app = express();

app.use(express.static("public"));

// parse post params sent in body in json format
app.use(express.json());

app.post("/my-server/create-paypal-order", async (req, res) => {
  try {
    const order = await paypal.createOrder();
    res.json(order);
  } catch (err) {
    res.status(500).send(err.message);
  }
});

app.post("/my-server/capture-paypal-order", async (req, res) => {
  const { orderID } = req.body;
  try {
    const captureData = await paypal.capturePayment(orderID);
    res.json(captureData);
  } catch (err) {
    res.status(500).send(err.message);
  }
});

app.listen(PORT, () => {
  console.log(`Server listening at http://localhost:${PORT}/`);
});

Sometimes the buttons are there and sometimes they are not,

When they are not, the iframe just disappears

How can I debug this issue?

enter image description here

enter image description here

Make popup div stackable

Hi all I have this popup that im inserting into the main div via function. Everything works okay if I call it only once, but what I want to do is to call it on every error so that every error has its own popup. If I do that now every popup is overlaying.

How can I make this popup stackable so they can be under each other if there is more than one?

The code is here

https://jsfiddle.net/s86nw4ct/6/

note I’m not using any frontend framework

let timer1, timer2;
const wrapper = document.getElementById('wrapper')



function showPopUp(title, body) {
  const popup_data =
    `<div class="toast active">
            <div class="toast-content">
                <i class="fas fa-solid fa-check check"></i>
                <div class="message">
                    <span id="text_title" class="text text-1">${title}</span>
                    <span id="text_body" class="text text-2">${body}</span>
                </div>
            </div>
            <i class="fa-solid fa-xmark close"></i>
            <div class="progress active"></div>
        </div>`

  wrapper.insertAdjacentHTML('beforeend', popup_data);

  const toast = document.querySelector(".toast");
  (closeIcon = document.querySelector(".close")),
  (progress = document.querySelector(".progress"));
  toast.classList.add("active");
  progress.classList.add("active");

  timer1 = setTimeout(() => {
    toast.classList.remove("active");
  }, 5000);

  timer2 = setTimeout(() => {
    progress.classList.remove("active");
  }, 5300);

  closeIcon.addEventListener("click", () => {
    toast.classList.remove("active");

    setTimeout(() => {
      progress.classList.remove("active");
    }, 300);

    clearTimeout(timer1);
    clearTimeout(timer2);
  });
}
* {
  margin: 0;
  padding: 0;
  overflow: hidden;
}

#wrapper {
  height: 100vh;
  width: 100vw;
}


/*popup part */

.toast:not(.showing):not(.show) {
  /*bootsratp overide */
  opacity: 1;
}

.toast {
  position: absolute;
  z-index: 10;
  top: 25px;
  right: 30px;
  border-radius: 12px;
  background: #fff;
  padding: 20px 35px 20px 25px;
  box-shadow: 0 6px 20px -5px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transform: translateX(calc(100% + 30px));
  transition: all 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.35);
}

.toast.active {
  transform: translateX(0%);
}

.toast .toast-content {
  display: flex;
  align-items: center;
}

.toast-content .check {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 35px;
  min-width: 35px;
  background-color: #4070f4;
  color: #fff;
  font-size: 20px;
  border-radius: 50%;
}

.toast-content .message {
  display: flex;
  flex-direction: column;
  margin: 0 20px;
}

.message .text {
  font-size: 16px;
  font-weight: 400;
  color: #666666;
}

.message .text.text-1 {
  font-weight: 600;
  color: #333;
}

.toast .close {
  position: absolute;
  top: 10px;
  right: 15px;
  padding: 5px;
  cursor: pointer;
  opacity: 0.7;
}

.toast .close:hover {
  opacity: 1;
}

.toast .progress {
  position: absolute;
  bottom: 0;
  left: 0;
  height: 3px;
  width: 100%;
}

.toast .progress:before {
  content: "";
  position: absolute;
  bottom: 0;
  right: 0;
  height: 100%;
  width: 100%;
  background-color: #4070f4;
}

.progress.active:before {
  animation: progress 5s linear forwards;
}

@keyframes progress {
  100% {
    right: 100%;
  }
}

button {
  padding: 12px 20px;
  font-size: 20px;
  outline: none;
  border: none;
  background-color: #4070f4;
  color: #fff;
  border-radius: 6px;
  cursor: pointer;
  transition: 0.3s;
}

button:hover {
  background-color: #0e4bf1;
}

.toast.active~button {
  pointer-events: none;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<div id="wrapper">
  <button type="button" onclick="showPopUp('test','body')">test</button>
</div>

How to replace backslashes in a regex saved as string, and to get it to work?

I have an array of names, which I use this regex /^[.*?[ЁёА-я].*?]/g filter to get those that only have Cyrillic letters in square brackets that occur at the start of the name (ex. reg1…test1 below) which works fine, I then save this regex to a database (sqlite3) as text. Now when I get it back from the table it is a string, which I need to replace with \ for the regex to work again.

I tried

  • .replace(/\/g, '\\');
  • .replace(/(?<!\)\(?!\)/g, '\\');
  • .replaceAll("\", "\\");

but as can be seen in this jsfiddle these don’t work as intended.

let arr = [
    '[Лорем ипсум долор] - Lorem ipsum dolor sit amet',
    '[Уллум велит ностер еи] sed do eiusmod tempor incididunt ut labore et dolore magna aliqua (X22)',    
    '[Пауло темпор те меа] Duis aute irure dolor (20X)',
    'Duis aute irure dolor (20X) [Пауло темпор те меа]',
    '[Lorem ipsum] sunt in culpa qui officia [Test]'
];

// Ok - this is before saving into the DB
let reg1 = /^[.*?[ЁёА-я].*?]/g;
let test1 = arr.filter(x => x.match(reg1));

// Ok - but I'd prefer not to save the regex in this form 
let reg2 = "^\[.*?[ЁёА-я].*?\]";
reg2 = new RegExp(reg2,'g');
let test2 = arr.filter(x => x.match(reg2));

// Ok - but no idea how to insert the regex part after the String.raw as 
// String.raw`${reg3}` doesn't work and String.raw(`${reg3}`) gives an error
let reg3 = String.raw`^[.*?[ЁёА-я].*?]`;
reg3 = new RegExp(reg3,'g');
let test3 = arr.filter(x => x.match(reg3));

// These don't work.
let reg4 = '^[.*?[ЁёА-я].*?]';
reg4 = reg4.replace(/\/g, '\\');
//reg4 = reg4.replace(/(?<!\)\(?!\)/g, '\\');
//reg4 = reg4.replaceAll("\", "\\");
reg4 = new RegExp(reg4,'g');
let test4 = arr.filter(x => x.match(reg4));

console.log({
    test1 : test1,
    test2 : test2,
    test3 : test3,
    test4 : test4
});

The correct result is the first three elements of the array like in the test1, test2, test3 results.

Any ideas on how to get a regex saved as a string : reg4 to work to get the correct output?

Canvas object changing color only sometimes

I’m making a visual representation of a “paper, rock, scissors” on canvas in Javascript. The point of it is that the objects will randomly flow on the canvas and when collision happens, rule from the original game will be applied. Paper = “beige”, rock = “gray”, scissors = “red”.
Now, the problem is – sometimes the objects are not changing their colors even when if is passing its statements fine – that’s my main problem. But they’re also sometimes are blocking each other and getting stuck.

At first, i thought that only paper (beige) is problematic, but now i don’t know.

I really hope you can find an answear for my problem and explain what am I missing 😀

canvas = document.getElementById('gameCanvas');
canvas.width = window.innerWidth / 2;
canvas.height = window.innerHeight / 2;
var ctx = canvas.getContext("2d");

let enemies = [];

class Obj {
    constructor(c) {
        this.x = 50 + Math.random() * canvas.width;
        this.y = 50 + Math.random() * canvas.height;
        this.w = 40;
        this.h = 50;
        this.c = c;
        this.vx = 1;
        this.vy = 1;
    }
    draw() {
        ctx.fillStyle = this.c;
        ctx.fillRect(this.x, this.y, this.w, this.h);
        ctx.beginPath();
        ctx.lineWidth = 50;
        ctx.strokeStyle = "black";
        ctx.stroke();
    }
    update() {
        if (this.x + this.w >= canvas.width) {
            this.vx = -1;
        }
        if (this.y + this.h >= canvas.height) {
            this.vy = -1;
        }
        if (this.y <= 0) {
            this.vy = 1;
        }
        if (this.x <= 0) {
            this.vx = 1;
        }
        this.x += this.vx;
        this.y += this.vy;
        this.draw()
    }

    bounceOffEachOther(other) {
        const dx = this.x + this.vx - other.x;
        const dy = this.y + this.vy - other.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        if (distance < this.w && this !== other) {
            this.vx = -this.vx;
            this.vy = -this.vy;
            if (this.c == "gray" && other.c == "red" || this.c === "red" && other.c == "grey") {
                //console.log("1 " + this.c + " " + other.c);
                this.c = "gray";
            } else if (this.c == "gray" && other.c == "beige" || this.c == "beige" && other.c == "grey") {
                //console.log("2 " + this.c + " " + other.c);
                this.c = "beige";
            } else if (this.c == "red" && other.c == "beige" || this.c == "beige" && other.c == "red") {
                //console.log("3 " + this.c + " " + other.c);
                this.c = "red";
            }
        }
    }
}


function createEnemies() {
    for (let i = 0; i <2; i++) {
        enemies.push(new Obj('grey'));
        enemies.push(new Obj('red'));
        enemies.push(new Obj('beige'));
    }
}
createEnemies();



function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    enemies.forEach(e => {
        e.update();
        enemies.forEach(other => e.bounceOffEachOther(other));
    });
}

function animate() {
    draw();
    requestAnimationFrame(animate);
}
animate();
<!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>Document</title>
</head>

<body>
    <center><canvas id="gameCanvas" style="border-style:solid; margin-top:10%"></canvas></center>
    <script src="script.js"></script>
</body>

</html>

I have an array of object and simple array with values, how can i add this value from array to each object in array of objects

type here

const array1 = [1, 2, 43, 5];

const arrayofObj = [
{
key: 1,
value: 3,
},
{
key: 2,
value: 10,
},
{
key: 3,
value: 20,
},
{
id: 123,
value: 30,
},
{
id: 123,
value: 30,
},
{
id: 123,
value: 30,
},
{
id: 123,
value: 30,
},
];

// i only come up with that:

]

const add = function(i) {
arrayofobj[i].val = array1[i] 
}

add(2)

// but it as you know only adds up to one specific index, so how can i add this value to all elements ? thanks for any help :)


i want to have something like that:

const arrayofobj = [
{
  key:1,
  value:2,
  val: (array1 element that have exact same index)

}