Remove Event Listener by Index HTML/Js [closed]

Hello how can i remove a Specific Event Listener from a HTML element.
In the Picture below are 3 Event Listeners attached to a Element and i want to remove the first one.
I want to make it in JavaScript and i know there are Methods like RemoveEventListener BUT i CANT access the original method because its external

i cant embed pictures yet

What is the best way to set the required attribute based on a state in React?

I’d like to set the required attribute on input based on a state, I tried something like the following:

const [required, setRequired] = useState(false)

return(
  <form onSubmit={submitHandler}>
    <input id='name' type='text' required={required} onChange={changeHandler} />
  </form>
)

At the moment, I can’t submit the form as the input is still required ‘even if my state is false’. What am I missing?
Thanks in advance!

How do I prevent elements with absolute position from overflowing?

I have attached a simple code snippet for a website. When hovering over the underlined words, images are supposed to appear. How can I prevent those images from “jumping out” of their container so that they will always be visible and don’t leave the screen?

The images are supposed to appear at the position of the correlating word.

I hope you understand the problem I’ve described here.

@charset "UTF-8";
/* CSS Document */

html, body {
    margin: 0;
    background-color: black;
}

#wrapper {
    margin: 0;
    position: fixed;
    width: 100%;
    height: 100%;
    overflow: scroll;
}

.section {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-content: center;
    align-items: center;
    justify-content: center;
    text-align: left;
    position: relative;
}

p {
    color: white;
    font-family: Helvetica, sans-serif;
    font-size: 36px;
    margin-left: 100px;
    margin-right: 100px;
    text-align: left;
    display: block;
    width: 50%;
}

.gallery-image {
    position: absolute;
    display: none;
    transform: translate(0,calc(1em - 50%));
  max-width: 50vw;
    max-height: 75vh;
    height: auto;
z-index: 1000;
}

.gallery-link {
  position: relative;
  text-decoration: underline;
}

.gallery-link:hover > .gallery-image{
    display: flex; 
z-index: 1000; 
}
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link href="styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="wrapper">
    
<div class="section">
<p>Title<br>
Nor is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain
<span class="gallery-link"><img  class="gallery-image" src="https://upload.wikimedia.org/wikipedia/commons/a/a0/590_Madison_Ave_IBM_08.jpg" >
vulnerability </span> of any.<br>
The once <span class="gallery-link">colorful rug<img class="gallery-image" src="https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/Ornamentglas_B_-_Ansicht_1.jpg/1000px-Ornamentglas_B_-_Ansicht_1.jpg"></span> has been <span class="gallery-link">broken down<img class="gallery-image" src="https://upload.wikimedia.org/wikipedia/commons/4/4a/Cocooningâ“’Shin%2C_Kyungsub.jpg" ></span> but is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain.<br>
End Quote
</p>
</div>          
</div>  

</body>
</html>

Why is form submission (register) not launching from my vuejs application ? Nothing in console

Thank you for your help.
I work on an application, I have to manage the frontend part with vue.js and the backend part with express.js, mysql.

One important thing I currently only work on requests in VueJS: Fetch API.
When I restart the front part and do a simulation nothing is displayed on my console.
I declared my data, method, fetch API.

-Authentication with Vue 3 : Registration and login.
-The page in question is the registration.
I then go to the backend to do the controllers, route, auth part, for secure authentication on mysql.

<script>
export default {
  name: "FormSuscribe",

  data() {
    return {
      first_name: "",
      email: "",
      password_key: "",
    };
  },

  methods: {
    signup() {
      fetch("http://localhost:3000/api/auth/signup", {
        method: "POST",
        //--Header--//
        headers: {
          Authorization: "Bearer ",
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        //---Body--//
        body: JSON.stringify({
          name: this.name,
          email: this.email,
          password: this.password,
        }),
      });
    },
  },
};
</script>
<template>
  <main>
    <section class="form my-4 mx-5">
      <div class="container">
        <div class="row">
          <div class="col-lg-5 g-0">
            <img
              src="@/assets/signup-image.jpg"
              class="img-fluid first-img"
              alt="Office"
            />
          </div>
          <div class="col-lg-7 px-5 pt-5">
         

            <form method="post" @submit="signup">
              <div class="form-row">
                <div class="col">
                  <input
                    id="first_name"
                    name="username"
                    placeholder="Nom"
                    class="my-3 p-2"
                    v-model="first_name"
                  />
                </div>
              </div>
              <div class="form-row">
                <div class="col">
                  <input
                    type="email"
                    id="email"
                    name="email"
                    class="form-group my-3 p-2"
                    placeholder="[email protected]"
                    v-model="email"
                  />
                </div>
              </div>

              <div class="form-row">
                <div class="col">
                  <input
                    type="password"
                    id="password"
                    name="password"
                    placeholder="**********"
                    class="my-3 p-2"
                    v-model="password_key"
                  />
                </div>
              </div>

              <div class="form-row">
                <div class="col-lg-4">
                  <button type="button" class="btn fw-bold">register</button>
                  <a href="">Forgot password</a>
                  <p>
                    You already have an account <a href="#">Connect</a>
                  </p>
                </div>
              </div>
            </form>
          </div>
        </div>
      </div>
    </section>

    <div class="container text-center">
      <img
        src="@/assets/icon-left-font-black.webp"
        class="img-fluid col-lg-2 col-sm-2"
        alt="Brand "
      />
    </div>
  </main>
</template>

How to sync vue.js data to global javscript variable

i currently work on an application with three.js and vue.js.

When i click on the 3d model a function gets triggered where the name of the clicked part of the model is set in the variable “name” which then should be rendered by vue.js.

On pageload the inital value of “name” in this example HELLO gets rendered. But when i click on the model the variable “name” gets updated but not the data variable “property” in vue.js.

How do i get reactivity to this example?

Greatful for every hint!

Javascript Part

var name = "HELLO". //defined as global variable


[...]

// Handling of click event in three.js

if (intersects.length > 0) {for(i = 1; i <= 6; i++) {
   if(intersects[ 0 ].object.name == 'K' + i ) { 
       //functions for specific parts are wrapped in an object to enable function call based on variable 'i'
      foo['K_' + i]('K' + i);         
}}

var foo = {
    K_1: function(i) {
         name = "foo_ " + i;
    },

    K_2: function() {},
    ...
}

vue.js Part

const app = Vue.createApp ({
    data() {
        return {
            property: name // object key "property" is set to var "name"
        }
    },

template: 
    `<h1> {{ property }} </h1>`
})

app.mount('#app')

Cant get DOM reference in svelte in function used in template

Im new to Svelte and a bit confused about the rendering in Svelte.
So I have this code:

<script>
 export let recipients: string[];
 let recipientsContainer: HTMLDivElement;
 const shouldRenderRecipient = (recipient) => {
  return !recipientsContainer?.textContent;
 }
</script>
<div>
 <div bind:this={recipientsContainer}>
  {#each recipients as recipient}
   {shouldRenderRecipient(recipient) ? recipient : ''}
  {/each}
 </div>
</div>

so what I expected would happen was that the view would be rendered and then the recipients would be looped and for each recipient itd check renderRecipient and depending on whether there was already a rendered recipient it would either throw true or false. But whats confused me is that the shouldRenderRecipient function is entered before we have a valid DOM reference for recipientsContainer.

I thought we would have access to recipientsContainer inside of shouldRenderRecipient function since shouldRenderRecipient function only gets called once the view is rendered?

Asychronous Javascript Problems

Could someone explain to me why the value of the variable user coordinates is a void value. I’ve based my code off of the solution of this:How to return the response from an asynchronous call

Any help would be appreciated.

function getLocation(callback) {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            var lat = position.coords.latitude;
            var long = position.coords.longitude;
            var uCoords = [lat, long];
            return callback(uCoords)
        });
    }
}

var userCoordinates= getLocation(function(position) {
    console.log(position)
    return position;
})

How do I replace the default action of Tab Key to move to next HTML textbox with my own JavaScript function

Take this HTML code, if you place your cursor on the 1st text-box, and then press Tab Key. The cursor will automatically jump to the 2nd text-box.

Box1:
<textarea id='box' cols='60' rows='10'></textarea>

Box2:
<textarea id='box' cols='60' rows='10'></textarea>

I need to replace this default action of switching to the next textbox with execution of JavaScript function I’ve defined. Let’s say: instead of switching textboxes execute function that writes ‘a’ on the the 1st text-box upon pressing Tab inside the box.

Any idea how I can make this happen?

D3 Add filling tto choropleth map based on values of csv

I am wondering how i can add colors to my colorpleth map, based on values of a csv file. I simply don’t get the point where i match those values to the different states of the us.

This is the json i used to create the map:
Json

My csv/Excel File looks like this:
States Column
With another Column named Shootings/Mio and values, which should represent the values for the individual colouring

Here you find my HTML

<!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>
    <link rel="stylesheet" href="./style.css">
    <script src="https://d3js.org/d3.v7.min.js"></script>
    <script src="https://d3js.org/topojson.v2.min.js"></script>
</head>
<body>
    <div class="home"></div>
    <script src="./test_script.js"></script>
</body>
</html>

And here you find my JS

let fetchData = async () => {
  dataset = d3.csv("Shootings.csv");
  return dataset;
};

const width = 900;
const height = 600;

const svg = d3
  .select(".home")
  .append("svg")
  .attr("width", width)
  .attr("height", height);

const projection = d3
  .geoAlbersUsa()
  .translate([width / 2, height / 2]) // translate to center of screen
  .scale([1000]); // scale things down so see entire US

const path = d3.geoPath().projection(projection);

fetchData().then((dataset) => {
  
  var Shootings = dataset.map(function(d){
    return d['ShootingsMio']
  })

  var states = dataset.map(function(d){
    return d['state_y']})

  var col_range_low = "#fff";
  var col_range_high = "#002837";

  var range_low = Math.min(...Shootings);
  var range_high= Math.max(...Shootings);

  console.log(Shootings)
  console.log(range_low)
  console.log(range_high)

  var color = d3.scaleLinear()
      .range([col_range_low, col_range_high])
      .domain([range_low,range_high])
      .interpolate(d3.interpolateLab);

  const tooltip = d3
    .select(".home")
    .append("div")
    .attr("class", "tooltip")
    .style("opacity", 0);

  const g = svg.append("g");

  d3.json(
    "https://gist.githubusercontent.com/Bradleykingz/3aa5206b6819a3c38b5d73cb814ed470/raw/a476b9098ba0244718b496697c5b350460d32f99/us-states.json"
  ).then((world) => {
    g.selectAll("path")
      .data(world.features)
      .enter()
      .append("path")
      .attr("d", path)
      .attr("class", "state")
      //.style("fill" How add filling based on the ShootingsMio column?
      })
      });

It looks like this momentanely
Server

If anyone could help me i would really appreciate that!

Cannot set value in chrome.storage

I have no idea why I can’t set a value in chrome.storage.sync (same issue with storage.local), I’ve tried multiple solutions online, but sadly none of them work

This is my popup.js file (linked to the popup.html file)

window.addEventListener("DOMContentLoaded", () => {
    let my_key = "some string";

    chrome.storage.sync.set({my_key: value}, function() {
        console.log('Value is set to ' + value);
    });

    chrome.storage.sync.get(['my_key'], function(result) {
        console.log('Value currently is ' + result.key);
    });

Everytime the output is Value currently is undefined.

Is there a way to save space on keys of JS objects?

I was just thinking about the following situation:

Let’s say we have a line definition like shown below. Here start and end are both points.

let line = {
    start: {x:0, y:0},
    end: {x:0,y:0},
    orientation: 'vertical'
}

Now imagine we have a very large array of lines, how do we save space? I know you can replace the orientation value 'vertical' with an Enum. But can you save space on the key names without reducing readability? E.g., you can replace orientation with o, but now it is no longer clear what the key stands for.

Let me know!

Close SQL connection Nodejs

I tried to close the connection for the below query by using connection.close(). but it is not working, so how to close connection inside route file

var express = require('express');
var router = express.Router();
var connection  = require('../database.js');
var db  = require('../database.js');


 
/* GET home page. */
 router.get('/', function(req, res, next) {
  connection.query("Select users..... ",function(err,supervisorrows)     {

             if(err){
          req.flash('error', err); 
          res.render('View',{page_title:"Users - Node.js",supervisor:''});   
         }else{
            
             res.render('View',{page_title:"Users - Node.js",supervisor:supervisorrows.recordset});

         }                     
        });




 
module.exports = router;

I can’t get the data of the user by his id

I can’t get the data from the API to display it on the screen when I try to retrieve it I get a 400 error I don’t know how to retrieve the data I put the right routes and so far nothing works.

import Card from "../../components/Card";
import styled from "styled-components";
import { Loader } from "../../utils/styles/Atoms";
import { useFetch, useTheme } from "../../utils/hooks";
import freelancers from "../Freelances";

const CardsContainer = styled.div`
  display: grid;
  gap: 24px;
  grid-template-rows: 350px 350px;
  grid-template-columns: repeat(2, 1fr);
  align-items: center;
  justify-items: center;
`;

const LoaderWrapper = styled.div`
  display: flex;
  justify-content: center;
`;

export function getFreelance(id) {
  const freelance = [];
  console.log(freelance);
  return freelance.find((freelancer) => freelancer.id === id);
}

function Freelance() {
  const { theme } = useTheme();
  const freelanceData = getFreelance();
  const { data, isLoading, error } = useFetch(
    `http://localhost:8000/profile/?id=${freelanceData}`
  );
  console.log(data);
  const freelanceProfil = data?.freelanceProfil;

  if (error) {
    return <span>Oups il y a eu un problème</span>;
  }
  return (
    <div>
      {isLoading ? (
        <LoaderWrapper>
          <Loader theme={theme} data-testid="loader" />
        </LoaderWrapper>
      ) : (
        <CardsContainer>
          {getFreelance((profile, index) => (
            <Card
              key={`${profile.name}-${index}`}
              label={profile.job}
              title={profile.name}
              picture={profile.picture}
            />
          ))}
        </CardsContainer>
      )}
    </div>
  );
}

export default Freelance;

/*The different routes to make API calls*/

/*
     Node Js API

          ul 
          li /freelances
          li /profile/?id={id}
          li /survey
          li /results/?a1={answer1}&a2={answer2}&a3={answer3}...
  */
/*The model to get the unique user using his Id*/

const freelancesData = require("../models/freelances");

function getFreelance(id) {
  return freelancesData.find((freelancer) => freelancer.id === id);
}

module.exports = getFreelance;

How to convert Excel Table to specific JSON format using Office Scripts

I’m trying to get a specific JSON output from Office Scripts in order to make an API call with Power Automate. The output I’m receiving from Power Automate does not have the format required in the API docs (link to API docs below). Tried modifying the script to get the required output but unfortunately, I’m just starting out with js, so I can’t figure out what I need.

Right now, the input must come from an Excel table. I can format the excel table differently for this flow if it’s needed, but nevertheless, the input must come from an Excel table. Right now, the Excel table looks like this:

This is the Office Script I am using, comes from this blog post: https://docs.microsoft.com/en-us/office/dev/scripts/resources/samples/get-table-data:

function main(workbook: ExcelScript.Workbook): TableData[] {
 // Get the first table in the "WithHyperLink" worksheet.
 // If you know the table name, use `workbook.getTable('TableName')` instead.
 const table = workbook.getWorksheet('WithHyperLink').getTables()[0];

 // Get all the values from the table as text.
 const range = table.getRange();

 // Create an array of JSON objects that match the row structure.
 let returnObjects: TableData[] = [];
 if (table.getRowCount() > 0) {
 returnObjects = returnObjectFromValues(range);
}

// Log the information and return it for a Power Automate flow.
console.log(JSON.stringify(returnObjects));
return returnObjects
}

function returnObjectFromValues(range: ExcelScript.Range): TableData[] {
 let values = range.getTexts();
 let objectArray : TableData[] = [];
 let objectKeys: string[] = [];
 for (let i = 0; i < values.length; i++) {
 if (i === 0) {
  objectKeys = values[i]
  continue;
}

let object = {}
for (let j = 0; j < values[i].length; j++) {
  // For the 4th column (0 index), extract the hyperlink and use that instead of text. 
  if (j === 4) {
    object[objectKeys[j]] = range.getCell(i, j).getHyperlink().address;
  } else {
    object[objectKeys[j]] = values[i][j];
  }
}

objectArray.push(object as TableData);
 }
 return objectArray;
}

interface TableData {
  "Event ID": string
  Date: string
  Location: string
  Capacity: string
  "Search link": string
  Speakers: string
 }

And this is the output I am getting in Power Automate when I run the Office Script:

[
 {
  "Line": "",
   "Id": "0",
   "Description": "nov portion of rider insurance",
   "Amount": "100",
   "DetailType": "JournalEntryLineDetail",
   "JournalEntryLineDetail": "",
   "PostingType": "Debit",
   "AccountRef": "",
   "value": "39",
   "name": "Opening Bal Equity"
 },
{
   "Line": "",
   "Id": "",
   "Description": "nov portion of rider insurance",
   "Amount": "100",
   "DetailType": "JournalEntryLineDetail",
   "JournalEntryLineDetail": "",
   "PostingType": "Credit",
   "AccountRef": "",
   "value": "44",
   "name": "Notes Payable"
 }
]

BUT, the schema I need looks like this (it is based on this API doc https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/journalentry):

{
 "Line": [
   {
     "Id": "0",
     "Description": "nov portion of rider insurance",
     "Amount": 100.0,
     "DetailType": "JournalEntryLineDetail",
     "JournalEntryLineDetail": {
     "PostingType": "Debit",
     "AccountRef": {
            "value": "39",
            "name": "Opening Bal Equity"
          }
    }
  },
  {
    "Description": "nov portion of rider insurance",
    "Amount": 100.0,
    "DetailType": "JournalEntryLineDetail",
    "JournalEntryLineDetail": {
    "PostingType": "Credit",
          "AccountRef": {
            "value": "44",
            "name": "Notes Payable"
          }

   }
  }
 ]
}

There are a lot of differences and obviously, when I try to make the API call, I get a 400 ‘Bad request’ error. Does anyone know how I must modify either the Script or the Excel table or do something different in Power Automate in order to get the specific schema I need?

Any help will be appreciated. Thanks!!