JS: select class inside of

I have an <iframe> on my page.

Inside of the page, that is loaded in the iframe, is this: <span class="test">TEST</span>

I would like to change the color of TEST to red.


This is what I wrote:

var test = document.querySelector("iframe").contentWindow.document.querySelector(".test");

test.style.color = "red";

Seems logical, but it doesn’t work. – What’s going on?

How to control number display format using Javascript?

I have a Javascript function that displays a time counter as the following : 0:0 and 0:1. But I actually want it to be displayed like this : 00:00 and 00:01.

Here is the code :

var interval = null;
var time = 0
function increaseTimer() {
    // increase and print timer
    time++
    console.log(new Date() + ' ' + 'timer: ' + parseInt(time / 60, 10) + ':' + parseInt(time % 60, 10))
    // condition of a process
    if (time % 5 == 0) {
        // some process
    }
    // stop simulation after 30s
    if (time == 30) {
        clearInterval(interval)
    }
}

I call this function with interval variable : interval = setInterval(increaseTimer, 1000)

What should I change in my code to make it work ?
Thanks in advance.

RxJS retry only last item, blocking the stream

I’m trying to use RxJS to process a stream of items, and I would like for it to retry any failures, preferentially with a delay (and exponential backoff if possible), but I need to guarantee the ordering so I effectively want to block the stream, and I don’t want to reprocess any items that were already processed

So I was trying to play with retryWhen, following this example:

const { interval, timer } = Rx;
const { take, map, retryWhen, delayWhen, tap } = RxOperators;

const source = take(5)(interval(1000));

source.pipe(
  map(val => {
    if (val >= 3) {
      throw val;
    }
    return val;
  }),
  retryWhen(errors =>
    errors.pipe(
      delayWhen(val => timer(1000))
    )
  )
);

But the stream restarts at the beginning, it doesn’t just retry the last one:

rxjs stream flowing

Is it possible to achieve what I want? I tried other operators from docs as well, no luck. Would it be kinda against RxJS philosophy somehow?

Only run write value at realtime database only once

            firebase.auth().onAuthStateChanged(function(user) { 
            if (user){
firebase.database().ref("users/" + user.uid).set({
            email:user.email, 
             points:"500",
            uid: user.uid
             })
   var query = firebase.database().ref("users").child(user.uid);
        query.once("value") .then(function(snapshot) {
              var email = snapshot.val().Email;
              var point = snapshot.val().points;
         document.getElementById("points").innerHTML=point;
        });


    

The code above is for writing and retrieving the data from database
but it is not going according to plans whenever there is changes on
points it automatically restores points to 500,, is there a way where a user’s data is written only once?

how to class component to functional components in react

I have some state and their setState also. but I wanna convert to the class component to the functional component but I don’t understand in setState how to do that.

state:

   constructor(posts) {
    super(posts);
    this.state = {
      data: posts,
      searchResultArray: [],
      cursor: {},
      currentResultIndex: 0,
    };
    this.onToggle = this.onToggle.bind(this);
  }

SetState:

plz, look this.setState my point is how to convert in functional components in the setState ?

onBtnClick = (e) => {
const { data, searchResultArray, currentResultIndex } = this.state;

let index = 0;
let tempObj = {};
if (e.target.id === "prev") {
  index = currentResultIndex - 1;
  tempObj = setSearchResult(data, searchResultArray, index);
  this.setState({
    data: tempObj.data,
    currentResultIndex: index,
    cursor: tempObj.cursor,
  });
}
if (e.target.id === "next") {
  index = currentResultIndex + 1;
  tempObj = setSearchResult(data, searchResultArray, index);
  this.setState({
    data: tempObj.data,
    currentResultIndex: index,
    cursor: tempObj.cursor,
  });
 }
};

RollupJS Output Not Recognizing External Package

I am having this issue where the output of my RollupJS package is throwing an error when it is run. Here is the Error:

Error: Command failed: node /path/to/test/package/root/index.js
/path/to/main/package/dist/cjs/index.js:33
const _tmpl$$3 = Web.template(`<div><h1>Error: </h1><p></p></div>`, 6);
                     ^

TypeError: Web.template is not a function
    at Object.<anonymous> (/Users/patrickluy/Documents/Business/Perivel/tools/solidus.js/packages/solidus/dist/cjs/index.js:33:22)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Module.require (internal/modules/cjs/loader.js:974:19)
    at require (internal/modules/cjs/helpers.js:101:18)
    at Object.<anonymous> (/Users/patrickluy/Documents/Business/Perivel/tools/solidus.js/packages/solidus-example-starter/dist/index.js:3:17)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)

Web is implying to the “solid-js/web” package I am depending on. I’m not actually sure why this is occuring. I followed the documentation on Rollup and included all my dependencies on the external and global options. Below is my Rollup configuration file:

export default [
  // lib
  {
    input: resolve(__dirname, 'index.ts'),
    treeshake: false,
    preserveEntrySignatures: false,
    external: [
      "@swindle/core",
      "@swindle/color",
      "express", ,
      'solid-js',
      'solid-js/web'
    ],
    output: [
      {
        format: "cjs",
        dir: resolve("dist/cjs"),
        sourcemap: true,
        globals: {
          'solid-js': 'solidjs',
          'solid-js/web': 'web',
          '@swindle/color': 'color',
          '@swindle/core': 'core',
          'express': 'express',
          'path': 'path'
        }
      },
      {
        format: "esm",
        dir: resolve("dist/esm"),
        sourcemap: true,
        globals: {
          'solid-js': 'solidjs',
          'solid-js/web': 'web',
          '@swindle/color': 'color',
          '@swindle/core': 'core',
          'express': 'express',
          'path': 'path'
        }
      },
      {
        name: "solidus",
        format: "umd",
        dir: resolve("dist/umd"),
        sourcemap: true,
        plugins: [terser()],
        globals: {
          'solid-js': 'solidjs',
          'solid-js/web': 'web',
          '@swindle/color': 'color',
          '@swindle/core': 'core',
          'express': 'express',
          'path': 'path'
        }
      },
    ],
    plugins: [
      nodePolyfillPlugin(),
      nodeResolve({
        extensions: [".js", ".ts", ".tsx"]
      }),
      babel({
        extensions: [".js", ".ts", ".tsx"],
        babelHelpers: "bundled",
        presets: ["solid", "@babel/preset-typescript"],
        exclude: "node_modules/**"
      })
    ]
  },
  
  // CLI
  {
    input: resolve(__dirname, 'cli.ts'),
    external: [
      "@swindle/core",
      "@swindle/color",
      "@swindle/os",
      "@swindle/filesystem",
      "express",
      "serve-static",
      "rollup",
      "@rollup/plugin-node-resolve",
      "@rollup/plugin-babel",
      "@rollup/plugin-json",
      "@rollup/plugin-typescript",
      "rollup-plugin-styles",
      "rollup-plugin-copy",
      "@web/rollup-plugin-import-meta-assets",
      "rollup-plugin-polyfill-node",
      "@rollup/plugin-image",
      // "solid-js",
      // "solid-js/web"
    ],
    output: [
      {
        file: "./dist/bin/solidus.js",
        format: "cjs",
        globals: {
          // globals
          // "@swindle/core": "swindleCore",
          // "@swindle/color": "swindleColor",
          // "@swindle/os": "swindleOS",
          // "@swindle/filesystem": "swindleFS",
          // "express": "express",
          // "serve-static": "serveStatic",
          // "rollup": "rollup",
          // "@rollup/plugin-node-resolve": "resolve",
          // "@rollup/plugin-babel": "babelPlugin",
          // "@rollup/plugin-json": "jsonPlugin",
          // "@rollup/plugin-typescript": "typescriptPlugin",
          // "rollup-plugin-styles": "stylesPlugin",
          // "rollup-plugin-copy": "copyPlugin",
          // "@web/rollup-plugin-import-meta-assets": "assetsPlugin",
          // "rollup-plugin-polyfill-node": "polyfills",
          // "@rollup/plugin-image": "imagePlugin",
          // "solid-js": "solid",
          // "solid-js/web": "web"
        }
      },
    ],
    plugins: [
      typescriptPlugin(),
      nodePolyfillPlugin(),
      jsonPlugin(),
      hashbangPlugin(),
    ],
  }
];

As you can see here, I have included both solid-js and solid-js/web as external dependencies, as per the documentation. However, this is still causing the output to throw the error.

I’m kind of at a loss as to how to resolve this. So, I’d appreciate any help.

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>

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')

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>

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;
})

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!