Change background with sliding transition depending on button hovered?

I’ve been trying to redesign my website recently, and I thought the idea to change the main header to change into different backgrounds depending on the button you hover would be cool

However, I know nothing about javascript besides from the absolute basic, so some help would be nice

Here’s what I’m trying to to achieve

enter image description here

Here’s the current HTML for the header

<body>
<div class="logocontainer">
 <a href="index.html">
 <img src="images/badasslogo.png" class="logo"></a>
 </div>

<div id="buttoncontainer" class="buttoncontainer">
</div>

<script src="js/menu.js"></script>

Here’s the CSS

.logocontainer {
    text-align: center;
   }

.logo {
    display: inline-block;
    margin-bottom: 0.30%;
    align: center;
   }

.buttoncontainer {
    text-align: center;
   }

.button {
    display: inline-block;
   }

.button:hover {
    box-shadow: 0 0 5px white;
    filter: brightness(125%);
   }
    
.button:active {
    box-shadow: 0 0 10px white;
    filter: brightness(155%);
   }

And the .js file which I use for the buttons, since if I didn’t use it, I would have to update every single page manually if I ever wanted to add more buttons to it

let headerContent = `
  <a href="index.html">
    <img src="images/buttons/homebutton.png" class="button"></a>

  <a href="blog/blogmain.html">
    <img src="images/buttons/blogbutton.png" class="button"></a>

  <a href="art/artmain.html">
    <img src="images/buttons/artbutton.png" class="button"></a>

  <a href="fanart/fanartmain.html">
    <img src="images/buttons/fanartbutton.png" class="button"></a>

  <a href="partners/partnersmain.html">
    <img src="images/buttons/partnersbutton.png" class="button"></a>
    
  <a href="guestbook/guestbook.html">
    <img src="images/buttons/guestbookbutton.png" class="button"></a>

  <a href="https://junessaidotnet.proboards.com/">
    <img src="images/buttons/forumsbutton.png" class="button"></a>
    
  <a href="downloads/downloadsmain.html">
    <img src="images/buttons/downloadsbutton.png" class="button"></a>
    
  <a href="extras/extrasmain.html">
    <img src="images/buttons/extrasbutton.png" class="button"></a>

  <a href="donate/donatemain.html">
    <img src="images/buttons/donatebutton.png" class="button"></a>
  
  <a href="about/about.html">
    <img src="images/buttons/aboutbutton.png" class="button"></a>
`;
document.querySelector('#buttoncontainer').insertAdjacentHTML('beforeend', headerContent);

Also, if possible
Is there any way to insert the logo into .js file aswell?

Updating component after submitting in React

I have an API to delete a service based on the given ID.

import axios from "axios";
import React from "react";
import swal from "sweetalert";
const useAddEditConferPatient = () => {
  let token = JSON.parse(localStorage.getItem("AuthToken"));
  const [response, setResponse] = React.useState();
  const fetchAddEditConfer = (
    id
  ) => {
    axios({
      method: "post",
      url: `${process.env.REACT_APP_API_URL_API_ADD_EDIT_CONFER_PATIENT}`,
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json",
      },
      data: 
         JSON.stringify({
          id
    
    })
      .then((r) => {
        setResponse(r.data);
        if (r.data.resCode === 1) {


          swal("success", "success");
        } else {
          swal("Error", "error");
        }
      })
      .catch(() => swal("Error", "error"));
  };
  return { fetchAddEditConfer, response };
};

export default useAddEditConferPatient;

it works but to see my updated list, I need to refresh the page after I do the operation. I want to make it real time without any refresh.

the list itself, comes from another API. it returns an array with objects, and I map it.

and here is the API:

import React from "react";
import axios from "axios";
export const useFetchListDetails = () => {
  let token = JSON.parse(localStorage.getItem("AuthToken"));
  const [listDetails, setListDetails] = React.useState();
  const HandleFetchDetails = (idConfer) => {
    axios({
      method: "post",
      url: `${process.env.REACT_APP_API_URL_API_LIST_SERVICECONFER}`,
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json",
      },
      data: JSON.stringify({
        idConfer: parseInt(idConfer),
      }),
    })
      .then((r) => {
        setListDetails(r.data.Data.ListService);
      })
      .catch(() => alert("Error"));
  };
  return { HandleFetchDetails, listDetails };
};

I tried to bring it to my deleting API. so if response is 1 it would delete the item and run the useFetchListDetails again.

but it didn’t work.

how can I solve this problem. I’m also not sure about, using state inside of hooks to return response. I don’t know if it is a bad practice or not.

Multiple results in object

I am currently struggling with a bracket position problem, I currently have a program that lists my employees and I need to add more data
at the moment this is my output :

[
  {
    gender: 'female',
    birthDate: '1999-01-09T01:03:14.158Z',
    name: 'Steven',
    surname: 'Johnson',
    workload: 30
  },
  {
    gender: 'male',
    birthDate: '1989-04-09T09:40:26.496Z',
    name: 'Jon',
    surname: 'Doe',
    workload: 20
  }
]

and I want it like this:

 {
  total: 50,
  workload10: 13,
  workload20: 12,
  workload30: 10,
  workload40: 15
  averageAge: 33.6,
  minAge: 19,
  maxAge: 55,
  medianAge: 38,
  medianWorkload: 28,
  averageWomenWorkload: 26,
  sortedByWorkload:[

  {
    gender: 'female',
    birthDate: '1999-01-09T01:03:14.158Z',
    name: 'Steven',
    surname: 'Johnson',
    workload: 30
  },
  {
    gender: 'male',
    birthDate: '1989-04-09T09:40:26.496Z',
    name: 'Jon',
    surname: 'Doe',
    workload: 20
  }
]
}

The problem is that I don’t know how to define the brackets to get this shape, can someone please advise me ?

mouseover evenlitsener is not fireing when i mover over elements

I’m trying to make a star rating system at an initial stage, the 5 star icon from font awesome deosn’t seem to fire when an even litsener to add to it, i don’t know what i’m doing wrong

html
`

<section class="mx-lg-3 pt-lg-5 pb-5" data-aos="fade-up">
    <div class="container mt-5">
        <div id="confirm-box">{% include "message.html" %}</div>
        <div class="row justify-content-center align-items-center">
            <div class="col-lg-5 col-md-6 mb-3">
                <img src="{{product.image.url}}" class="w-100" alt="product image">
            </div>
            <div class="col-lg-3 col-md-5 product-details">
                <p class="sale text-center">Sale</p>
                <h2>{{product.name|title}}</h2>
                <p>Product id: {{product.id}}</p>
                <div class="ratings">
                    <span class="fa fa-star checked" id="first"></span>
                    <span class="fa fa-star checked" id="second"></span>
                    <span class="fa fa-star checked" id="third"></span>
                    <span class="fa fa-star-half-stroke checked" id="fourth"></span>
                    <span class="fa fa-star" id="fifth"></span>
                </div>
                <p class="product-price">USD ${{product.price}}</p>
                <label for="">Quantity: </label>
                <input type="text" readonly id="product-quantity" value="{{current_item.quantity}}">
                <button id="update-cart" data-product={{product.id}} data-action="add" class="btn add-btn update-cart">Add to cart</button>
            </div>
        </div>
    </div>
</section>

Javascript

`

const one = document.getElementById('first')
const two = document.getElementById('second')
const three = document.getElementById('third')
const four = document.getElementById('fourth')
const five = document.getElementById('fifth')

const arr = [one, two, three, four, five]

one.addEventListener('mouseover', function(event){
    console.log(event.targetS)
    console.log('event is working')
})

arr.forEach(function(item) {
    item.addEventListener('mouseover', function(event) {
        console.log(event.target)
    })

}) 

i’ve tried it with just one of the element and it still doesn’t fire

MongoDB : FindOne() return null but the document exist Discord.js V14

I am creating a giveaway system, I use mongo DB with the node module mongoose to store the giveaway data using this code :

await DB.create({
          GuildID: interaction.guild.id,
          MessageID: message.id,
          ChannelID: interaction.channel.id,
          EndTime: formattedDuration,
          Ended: false,
          HostedBy: interaction.user.id,
          Prize: prize,
          Winners: winners,
          Paused: false,
          Entered: [],
        })

it create the doc successfully in the database

in a separated command I use this code to get the giveaway data

also I am sure that the Message ID given is correct

          const data = await DB.findOne({
            GuildID: interaction.guild.id,
            MessageID: messageId
          });
          console.log(data);

But it return null

I tried

findById()

but the same it return null

I am using discord.js v14.7.1 & mongoose v6.7.5 & node v18.12.1

Saving answers to Localstorage when submitted

I need to save users answers to local storage which could be read after closing the page. I have json file with questions and options and I initialized a let variable containing them at the beginning of script section. I don’t know how to make a relation between submitting form, localstorage and event listener.

Thank you,
Marija

Here is my code.

<body>
        <form id="quiz">
        </form>
     <script>
     
let quiz = document.getElementById("quiz");
let array = Object.keys(json.quiz);
for (let j = 0; j < array.length; j++) {
  let key = array [j];
  let questionItem = json.quiz[key];
  let html = "<div>";
  html += "<div><h2>Question " + (j + 1) + ": " + questionItem.question + "</h2></div>";
  html += "<div>";
  for (let i = 0; i < questionItem.options.length; i++) {
    html += "<div>";
    html += "<input type="radio" name="" + key + "_option"  value="" + questionItem.options[i] + "">" + questionItem.options[i];
    html += "</div>";
  }
  html += "</div>";
  html += "</div>";
  
 quiz.innerHTML += html;
}
quiz.innerHTML += "<input type="submit" value="submit">";
  


    </script>    
    </body>

React render data that received from electron after window reload

I am writing app that read all istalled apps on windows and renders it. After app launch it returns empty array. But after reload window react render programs from array. How can I fix this?

ActionForm.js:

import React, { useState } from "react";

const ActionForm = () => {
  const [programs, setprograms] = useState([]);
  window.app.receive("user:programs", function (res) {
    setprograms(res);
    console.log(programs);
  });
  return (
    <div>
      {programs.map((program) => (
        <h6 key={program.name}>{program.name}</h6>
      ))}
    </div>
  );
};

export default ActionForm;

programs.js:

const process = require("node:process");
const fs = require("node:fs");
const path = require("node:path");

function isDirectory(folder) {
  fs.lstat(
    path.join(
      `${process.env.ProgramData}/Microsoft/Windows/Start Menu/Programs`,
      folder
    ),
    (err, stat) => {
      if (err) {
        console.log(err);
      }

      return stat.isDirectory();
    }
  );
}

function getListOfPrograms() {
  let result = [];
  fs.readdir(
    `${process.env.ProgramData}/Microsoft/Windows/Start Menu/Programs`,
    function (err, folders) {
      if (err) {
        console.log(err);
      }
      folders.forEach((programFolder) => {
        if (!isDirectory(programFolder)) {
          result.push({ name: programFolder });
        } else {
          fs.readdirSync(
            `${process.env.ProgramData}/Microsoft/Windows/Start Menu/Programs/${programFolder}`
          ).forEach((program) => {
            result.push({ folder: programFolder, name: program });
          });
        }
      });
    }
  );
  return result;
}

module.exports = getListOfPrograms();

index.js:

    const programs = require('../Utils/programs')
    subscribe() {
        Object.keys(EVENTS).forEach(event => {
            ipcMain.setMaxListeners(ipcMain.getMaxListeners() + 1)
            ipcMain.on(event, (e, data) => EVENTS[event].call(this, e, data))
        })
        this.Window.send("app:ready")
        this.Window.send('server:status', this.Server.Network.serverStatus)
        this.Window.send('user:programs', programs)
    }

    quit() {
        this.Window.Window.removeAllListeners('close')
        this.Window.Window.close()
    }

    on(event, listener) {
        app.on(event, listener)
    }
}

In subscribe window runs getListOfPrograms and sends it. Than ActionForm.js receives it and renders.

Change img with javascript loop

On my website normally there are two default images and I want whenever I click an H3 element to change the 2 default images with img1 or img2 … the problem is when I click the h3 to change the 2 default imgs to img1 for example it changes only the first one so I tried to use loop but I didn’t know how exactly because I’m a beginner in javascript can you please help me create a loop function using my code to change all the default images in the site to img1 or img2 … when I click to h3

<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>

<body>
<h3 onclick="ShowImg1();">Click Here To Show IMG 1</h3>
<h3 onclick="ShowImg2();">Click Here To Show IMG 2</h3>
<h3 onclick="ShowImg3();">Click Here To Show IMG 3</h3>
<h3 onclick="ShowImg4();">Click Here To Show IMG 4</h3>

<!-- img section n#1 -->
<span id="defaultimg"><p><img alt="deffault-img" src="https://i.ibb.co/kqjt7wM/default-img.png"></p><br></span>
<span id="exp1img" style="display: none;"><p><img alt="img1" src="https://i.ibb.co/wcdx6pt/img1.png"></p><br></span>
<span id="exp2img" style="display: none;"><p><img alt="img2" src="https://i.ibb.co/XpFmqGT/img2.png"></p><br></span>
<span id="exp3img" style="display: none;"><p><img alt="img3" src="https://i.ibb.co/yp0jvKS/img3.png"></p><br></span>
<span id="exp4img" style="display: none;"><p><img alt="img4" src="https://i.ibb.co/6bYs2Jh/img4.png"></p><br></span>


<!-- img section n#2 -->
<span id="defaultimg"><p><img alt="deffault-img" src="https://i.ibb.co/kqjt7wM/default-img.png"></p><br></span>
<span id="exp1img" style="display: none;"><p><img alt="img1" src="https://i.ibb.co/wcdx6pt/img1.png"></p><br></span>
<span id="exp2img" style="display: none;"><p><img alt="img2" src="https://i.ibb.co/XpFmqGT/img2.png"></p><br></span>
<span id="exp3img" style="display: none;"><p><img alt="img3" src="https://i.ibb.co/yp0jvKS/img3.png"></p><br></span>
<span id="exp4img" style="display: none;"><p><img alt="img4" src="https://i.ibb.co/6bYs2Jh/img4.png"></p><br></span>


</body>

<script>
function ShowImg1() {
const visibility = "block";
const novisibility = "none";
document.getElementById("exp1img").style.display=visibility ;
document.getElementById("defaultimg").style.display=novisibility ;
document.getElementById("exp2img").style.display=novisibility ;
document.getElementById("exp3img").style.display=novisibility ;
document.getElementById("exp4img").style.display=novisibility ;
}
function ShowImg2() {
const visibility = "block";
const novisibility = "none";
document.getElementById("exp2img").style.display=visibility ;
document.getElementById("defaultimg").style.display=novisibility ;
document.getElementById("exp1img").style.display=novisibility ;
document.getElementById("exp3img").style.display=novisibility ;
document.getElementById("exp4img").style.display=novisibility ;
}
function ShowImg3() {
const visibility = "block";
const novisibility = "none";
document.getElementById("exp3img").style.display=visibility ;
document.getElementById("defaultimg").style.display=novisibility ;
document.getElementById("exp2img").style.display=novisibility ;
document.getElementById("exp1img").style.display=novisibility ;
document.getElementById("exp4img").style.display=novisibility ;
}
function ShowImg4() {
const visibility = "block";
const novisibility = "none";
document.getElementById("exp4img").style.display=visibility ;
document.getElementById("defaultimg").style.display=novisibility ;
document.getElementById("exp2img").style.display=novisibility ;
document.getElementById("exp3img").style.display=novisibility ;
document.getElementById("exp1img").style.display=novisibility ;
}
</script>

</html>

Rendering a popup after clicking an other component

I have a component named Card, and a const boolean variable named auth to refer the status of authorization of user. If user is not logged in, the auth is false.

When auth is false, and if user clicks on one of the Card components, I want to show him an popup that he should be register if he wants to click on a Card.

Here is my Card component:

import * as React from 'react';
import {useState} from 'react';
import './card.css';
import HeartButton from "./HeartButton";

import { StyledEngineProvider } from '@mui/material/styles';


import Modal from './Pop';


const Card = ({ profile, auth }) => {

  const handleClick = () => {
    // RENDER COMPONENT MODAL HERE
    // MODAL SHOULD BE RENDERED IF AND ONLY IF AUTH IS FALSE
  }

  return (
    <div className='influencer-profile-card' onClick={handleClick}>

      <div>
        <HeartButton/>
      </div>

      <div className="profile_picture">
        <img src={profile.picture !== 'N/A' ? profile.picture : 'https://via.placeholder.com/400'} alt={profile.name} />
      </div>

      <div className="info">
        <h3>{profile.name}</h3>
        <h4>{profile.ID + " • " + profile.category}</h4>
      </div>

    </div>
  )
}

export default Card

and here is the Modal:

import * as React from 'react';
import Backdrop from '@mui/material/Backdrop';
import Box from '@mui/material/Box';
import Modal from '@mui/material/Modal';
import Fade from '@mui/material/Fade';
import Button from '@mui/material/Button';
import Typography from '@mui/material/Typography';

import "./popup.css";

function TransitionsModal(auth) {
    const [open, setOpen] = React.useState(auth);
    const handleClose = () => setOpen(false);

    return (
        
        <div>
            <Modal
                aria-labelledby="transition-modal-title"
                aria-describedby="transition-modal-description"
                open={open}
                onClose={handleClose}
                closeAfterTransition
                BackdropComponent={Backdrop}
                BackdropProps={{
                timeout: 500
            }}>
          <Fade in={open}>
                    <div className="popup-container" id='blur'>
                        <h1>Profil detaylarını görebilmek için lütfen giriş yapınız.</h1 >
                        <div className='popup-buttons'>
                            <a className='giris-yap-wrapper' href="/signIn">
                                <input
                                    type="submit"
                                    value="Giriş Yap"
                                    className="popup-input-login"
                                    onclick="togglePopup()"/>
                            </a>
                            <input type="submit" value="Vazgeç" className="popup-input" onClick={handleClose}/>

                        </div>
                    </div>
                </Fade>
            </Modal>
        </div>
    );
}

export default TransitionsModal;

I’m new to react and I can’t figure out how to code this. Please help me

React: Passing a dictionary of functions but somehow failing to access it correctly

I have an App component where I define two functions A and B.

I am then passing these two functions to a Card component as follow

          <Card 
            key = {el.key} 
            item={el} 
            onPress={{
                select : ()=>A(el.key),
                discard : ()=>B(el.key)
          }}
          />

however, for some reason, when inside my Card i do something like

    ....
    <div 
        className={className} 
        onClick={props.onPress.select}>
    </div>
    ...

I get this nasty error


react-dom.development.js:18687 The above error occurred in the <Card> component:

    at Card (http://localhost:5174/src/components/Card.jsx?t=1670102247232:33:48)
    at div
    at div
    at div
    at App (http://localhost:5174/src/App.jsx?t=1670102247232:24:31)

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
react-dom.development.js:26923 Uncaught TypeError: Cannot read properties of undefined (reading 'select')
    at Card (Card.jsx:28:32)
    at renderWithHooks (react-dom.development.js:16305:18)
    at mountIndeterminateComponent (react-dom.development.js:20074:13)
    at beginWork (react-dom.development.js:21587:16)
    at beginWork$1 (react-dom.development.js:27426:14)
    at performUnitOfWork (react-dom.development.js:26557:12)
    at workLoopSync (react-dom.development.js:26466:5)
    at renderRootSync (react-dom.development.js:26434:7)
    at recoverFromConcurrentError (react-dom.development.js:25850:20)
    at performConcurrentWorkOnRoot (react-dom.development.js:25750:22)


what am I doing wrong?

How to get larger doubles in Javascript

I am trying to caculate pi to a large amount of decimal places using the Gauss–Legendre algorithm as seen below

enter image description here

However, it only gives back around 15 digits of pi. Apparently this is because Mathematical operations in Javascript are performed using 64-bit floating point values and 16 digits of precision is right around the limit of what they can represent accurately.

This is my code

let a = 1,
    b = 1 / Math.sqrt(2),
    t = 1 / 4,
    p = 1;

let i = 0;
while (a - b < 3) {
    i++;

    let an = (a + b) / 2;
    b = Math.sqrt(a * b);
    t = t - p * (a - an) ** 2;
    p = 2 * p;

    a = an;

    if (i == 100) break;
    let pi = (a + b) ** 2 / (4 * t);
    console.log(pi);
}

I was wondering if there was any work around to get javascript to return more digits of pi.
Thanks in Advance

Typescript: Unknown address type. Byte length is not 36

I am running a script and I see the following error that the address type is unknown. I am new to typescript so if there is any information needed about Address type let me know:

yarn ts-node manage/deploy-sandbox.ts
yarn run v1.22.19
$ /Users/apple/proj/tonstart/node_modules/.bin/ts-node manage/deploy-sandbox.ts
/Users/apple/proj/tonstart/node_modules/ton/dist/address/Address.js:17
    throw new Error('Unknown address type: byte length is not equal to 36');
          ^
Error: Unknown address type: byte length is not equal to 36
    at parseFriendlyAddress    (/Users/apple/proj/tonstart/node_modules/ton/dist/address/Address.js:17:15)

deploy-sandbox.ts:

import { Cell, contractAddress, StateInit, toNano, beginCell, Address } from  'ton';
import { readFileSync } from 'fs';
import qs from 'qs';
import qrcode from 'qrcode-terminal';

// Create a data cell similar to the initial contract state
const dataCell = beginCell()
.storeUint(0, 32)                        // counter
.storeAddress(Address.parse('/* YOUR ADDRESS */'))
.endCell();

// Load code from build
const codeCell = Cell.fromBoc(readFileSync('./build/hello-world.boc'))[0];

// Calculate address from code & data
const address = contractAddress({
    workchain: 0,
    initialCode: codeCell,
    initialData: dataCell
});

// Prepare init message
const initCell = new Cell();
new StateInit({
code: codeCell,
data: dataCell,
}).writeTo(initCell);

// Encode link to deploy contract
let link = 'https://test.tonhub.com/transfer/' + address.toFriendly({ testOnly: true }) + '?' + qs.stringify({
text: 'Deploy contract',
amount: toNano(1).toString(10),
init: initCell.toBoc({ idx: false }).toString('base64')
});
console.log('Address: ' + address.toFriendly({ testOnly: true }));
qrcode.generate(link, { small: true }, (code) => {
 console.log(code)
});

I was expecting the script to execute. I just tried running it that’s all.

How to decode the request from frontend?

I get the following payload (part of payload I had pasted below):

images%5B2bbe51ff-27ee-4a71-bfeb-97ceaf8a6698.png%5D=iVBORw0KGgoAAAANSUhEUgAAAhIAAAISCAIAAAAWX7HoAAEAAElEQVR4nOz9Wa%2BuWZIehkWs8Z2%2Bec97nzHnyszqGrq7eh5oUSJpWRDJC8uSDBge4QvCEATYhATD8IUHyIZgygQow5RlUxQsAYRINt0DWxTJ6upmdVVX1pBz5pnP2fP%2B5ndeQ4Qv8qSB%2BgG%2Bq7jZt%2FvBelc8EU88sT6An8XP4mfxs%2FhZ%2FCx%2BFj%2BLn8XP4mfxs%2Fj%2FR%2BAXf%2F7m%2F%2B5%2F7OdLlYUdPeU8TQ0ioBQQZV4UnEj2LB2Zm%2Fa0vG

There should be the base64 encoded images. How I can decode it?
Fast API Form(…) or File(…) give me 422 Unprocessable Entity