How to access the input tag value

How to access the value after pay now $ in the tag with id payment-sub-btn in the code below to payModal() function I have finalPrice variable finalPrice = document.getElementById('payment-sub-btn').textContent; I try using by getting element by id but it says NaN probably cause its getting the text as well pay now $ with it is there any way to just get the value which is integer value and no text along with it?

 <div class="modal-body" style="background-color: #F6F9FC">
            {{-- Display a Payment Form --}}
            <form method="post" id="payment-form" class="m-1" data-secret="123">
    
              <div class="card-element-hide form-group col-md-12">
    
                <div id="payment-element" class="w3-block" style="min-width:300px!important">
                  <!-- Mount the Payment Element here -->
                </div>
    
              </div>
    
              <div id="coupon-details" class="col-md-12">
                <label class="stripeFontStyle" for="feCoupon"> Coupon Code </label>
                <input type="text" class="form-control form-control-sm stripeBoxStyle" id="lost_coupon"
                  onChange="checkCoupon()" name="lost_coupon" data-dpmaxz-eid="10">
                <p style="visibility:hidden; margin-left:5px;" id="couponMessage"></p>
              </div>
          </div>
          <div class="modal-footer">
            <button class="btn btn-secondary boxShadow" data-dismiss="modal"><i class="fa-solid fa-circle-xmark"></i>
              Close</button>
             
            <button id="payment-sub-btn" class="btn btn-success float-right" style="background-color:#28a745!important"
              onclick="update_coupon();">Pay Now $</button>
            </form>
          </div>

    <script>
    async function payModal() {
      
      await fetch("{{ route('paymentModal') }}")
      .then(response => response.json())
        .then(response => {
          const form = document.getElementById('payment-form');
          _key_for_ss = response.paymentIntent.client_secret;
          paymentIntentID = response.paymentIntent.id;
          finalPrice = document.getElementById('payment-sub-btn').textContent;
          async function openModal() {
            await createCard();
            $('#pay-modal').modal('show');
          }
          openModal();
        })
    }

     var counts = 1;
     var checkboxes;
     var finalPri;
    function add_to_download_entries(data) {
       checkboxes = document.querySelectorAll('input[name="checkWills"]:checked');
        counts = checkboxes.length;
      if($.inArray(data, selected_lostwill_array) >= 0){
        selected_lostwill_array = $.grep(selected_lostwill_array, function(value){
             return value != data;
           });
         }else{
          selected_lostwill_array.push(data);
         }
         // DataTables Functions 
    $(document).ready( function () {
        $('#org_lost_table').DataTable();
        $('#all_lost_table').DataTable();
        if(counts>0){
             finalPri = "Pay Now $" + Number(counts) * Number(22);
            
            $( "#payment-sub-btn" ).text(finalPri);
           }else $( "#payment-sub-btn" ).text(0); 
    } );
    }
    </script>

Using the regexp /.?0+$/, why are the zeros in “500” not a match?

The code below is working perfectly: it should remove unnecessary trailing zeros at the end of the decimal part of a number.

`    let solution = math.evaluate(inputValue);
    
    input.value = solution.toFixed(8).replace(/.?0+$/, '');`

I’m trying to understand the regular expression better. If the operator “?” indicates that the dot (.) is optional, it may or may not appear, so why doesn’t this code strip the zeros from a string like “500”? It would be a bug, but I can’t understand why it doesn’t happen.

Ie: With the string “5.00”, the zeros will be removed, but with “500”, no. This seems to contradict that the presence of the dot is optional for a match to occur in the regexp.

Request timed out when deployed nodejs server online

I have 2 parts of this code, I am not sure where the error comes from or how to diagnose it, my code works fine on my localhost and returns the data correctly and it shows up on my front end without issue.

When I deployed the server to render.com (free plan) I got this issue

[Error: The request timed out.]

I tried fixing the root of the server like so

const server =  app.listen(port, () => {
  console.log(`Running server at port: ${port}`);
});

server.setTimeout(120000); // 120 seconds timeout

Then on the api endpoint there’s 2 functions, added axios timeout functionality because of the issue, for ffmepg I am not sure how to fix it

router.post("/", async (req, res) => {
  var videoUrl = req.body.video;

  const videoResponse = await axios.get(videoUrl, {
    responseType: 'arraybuffer',
  });

  const formData = new FormData();
  formData.append('file', Buffer.from(videoResponse.data), {
    filename: 'video.mp4',
  });
  formData.append('model', model);
  formData.append('response_format', 'srt');

  const headers = {
    'Authorization': `Bearer ${token}`,
    ...formData.getHeaders(),
  };

  const response = await axios.post('https://example.com', formData, {
    headers,
      timeout: 1200000
  });

  fs.writeFileSync('transcription.srt', response.data);
  console.log('Transcription saved to transcription.srt');

  const subtitlePath = "./transcription.srt";
  console.log('subtitlePath :', subtitlePath);

  const randomNum = Math.floor(100000000000 + Math.random() * 900000000000);
  const fileName = `video_${randomNum}.mp4`;
  const outputPath = `./${fileName}`;

  // Execute the ffmpeg command to burn the subtitles into the video
  const ffmpeg = spawn("ffmpeg", [
    "-i",
    "pipe:0",
    "-vf",
    `subtitles=${subtitlePath}:force_style='Alignment=10,OutlineColour=&H100000000,BorderStyle=3,Outline=1,Shadow=0,Fontsize=10'`,
    "-c:a",
    "copy",
    "-progress", "pipe:1",
    outputPath,
  ]);

  // Pipe the videoResponse array buffer to FFmpeg
  ffmpeg.stdin.write(videoResponse.data);
  ffmpeg.stdin.end();

  // Send the output file as a response once the process is complete
  ffmpeg.on("close", () => {
    fs.readFile(outputPath, (err, data) => {
      if (err) {
        console.error(err);
        res.status(500).send("Failed to read the file");
      } else {
        res.set({
          "Content-Disposition": `attachment; filename=${outputPath}`,
          "Content-Type": "application/octet-stream",
        });
        res.send(data);
        console.log("File sent successfully");
        // Delete the output file once it has been sent
        fs.unlinkSync(outputPath);
      }
    });
  });
});

module.exports = router;

On my react native app, I added promise and some timeout code just to make sure the error it’s not originated from there but still facing the same issue

testing = (downloadURL) => {
    const timeoutPromise = new Promise((_, reject) => {
      setTimeout(() => {
        reject(new Error('Request timed out'));
      }, 120000); // 120 seconds timeout
    });

    this.setState({ loading: true, uploading: false });
    RNFetchBlob.config({
      fileCache: true,
      appendExt: 'mp4',
    })
      .fetch('POST', 'https://example.com/api/v1/test', {
        'Accept': 'application/octet-stream',
        'Content-Type': 'application/json',
      }, JSON.stringify({
        video: downloadURL,
      }))
      .then(response => {
        const videoPath = response.path();
        const videoUrl = `file://${videoPath}`;
        console.log('videoUrl :', videoUrl);
        this.setState({ loading: false, success: true, render: videoUrl, downloadURL: null });
      })
      .catch(error => {
        console.log(error);
        this.setState({
          error: error.message,
          loading: false,
        });
      })
      .finally(() => {
        clearTimeout(timeoutId);
      });

    const timeoutId = setTimeout(() => {
      console.log('Request timed out');
      this.setState({
        error: 'Request timed out',
        loading: false,
      });
    }, 120000); // 120 seconds timeout

    Promise.race([timeoutPromise])
      .catch(error => {
        console.log(error);
        this.setState({
          error: error.message,
          loading: false,
        });
      });
  };

Now to describe the problem, after triggering the endpoint the api is running fine then start the axios post request, this part is very fast and get done in about 2-3 seconds, the file then is moved to ffmpeg for converting, I have the code below that allows me to check conversion status progress, usually from what I see is when percentage is about to hit 100% I got the error timed out on my fronend and on the server it shows

POST /api/v1/test – – ms – –

No error on console log whatesover

   // Listen to stderr and stdout data events to check the progress of the conversion
  let progress = 0;
  let duration = 0;
  ffmpeg.stderr.on('data', (data) => {
    // Search for the "Duration" line to get the total duration
    const durationMatch = /Duration: (d{2}):(d{2}):(d{2})/.exec(data.toString());
    if (durationMatch) {
      duration = (parseInt(durationMatch[1]) * 3600) + (parseInt(durationMatch[2]) * 60) + parseInt(durationMatch[3]);
    }

    // Search for the "time=" line to get the current time
    const timeMatch = /time=(d{2}):(d{2}):(d{2})/.exec(data.toString());
    if (timeMatch) {
      const currentTime = (parseInt(timeMatch[1]) * 3600) + (parseInt(timeMatch[2]) * 60) + parseInt(timeMatch[3]);
      progress = Math.floor((currentTime / duration) * 100);
      console.log(`FFmpeg     : ${progress}%`);
    }
  });

Please help. Any suggestions appreciated

How do I make text turn into a new element (Like a divider) onclick?

I’m trying to find a way to make some text on my page turn into a divider/new element when I click it. I’m not sure how to explain it, but like, imagine an image with a caption beneath – You click the caption then the image above becomes like a box of text/a different image/a scrollable divider. I’m trying to achieve the effect of the page here, in which clicking the skull emoji on the right results in a new div / image appearing in the box on the left. I’m looking through the source code & inspecting what she did to make this effect and I’m still unsure what.

I was attempting something using the w3schools onclick guide

`<img src="yay.png">
<p id="angelo" onclick="myFunction()">ANGELO</p>
<script>
function myFunction() {
document.getElementById("angelo") InnerText =" <div id="info"> Blabla </div> " ;
}
</script>`

I don’t know much at all about java- infact i have only used it once! so this didn’t aid me by any means of the word as I was just attempting to figure out some way to make it work, though I have a strong feeling i’m doing it wrong.

JS Prisma register user in database, crashing when username fails unique constraint in unwanted ways – not using error function designed

When creating a new user. I am testing the error functions. Creating a user works fine.
I am testing to see what happens when i register as a new user with a username already in use.
Instead of using my (!createdUser) function that sends an error message to the user.
The code skips and goes right to the error section of my try/catch.
Returning a 500 error. However this error completely crashes my database connection. The error log i have claim show it write the logs but they dont get added to the database either.

It is supposed to return a message to the user. Also now i think about it, is there a way i can have my response say username is already in user, to the user that is.

  console.log('Registering new user');

  const {
    email,
    password,
    username,
    firstName,
    lastName,
    city,
    country,
    gender,
    dob,
    profileImage,
    bio,
    agreedToTerms,
  } = req.body;

  const lowerCaseEmail = email.toLowerCase();
  const lowerCaseUsername = username.toLowerCase();
  const lowerCaseFirstName = firstName.toLowerCase();
  const lowerCaseLastName = lastName.toLowerCase();
  const lowerCaseCity = city.toLowerCase();
  const lowerCaseCountry = country.toLowerCase();

  try {
    if (
      !lowerCaseEmail ||
      !password ||
      !lowerCaseUsername ||
      !lowerCaseFirstName ||
      !lowerCaseLastName ||
      !lowerCaseCity ||
      !gender ||
      !dob ||
      !lowerCaseCountry ||
      !agreedToTerms
    ) {
      //
      const missingField = new MissingFieldEvent(
        null,
        'Registration: Missing Field/s event'
      );
      myEmitterErrors.emit('error', missingField);
      return sendMessageResponse(res, missingField.code, missingField.message);
    }

    const foundUser = await findUserByEmail(lowerCaseEmail);
    if (foundUser) {
      return sendDataResponse(res, 400, { email: EVENT_MESSAGES.emailInUse });
    }

    const hashedPassword = await bcrypt.hash(password, hashRate);

    const createdUser = await createUser(
      lowerCaseEmail,
      hashedPassword,
      lowerCaseFirstName,
      lowerCaseLastName,
      lowerCaseCountry,
      lowerCaseCity,
      lowerCaseUsername,
      gender,
      dob,
      agreedToTerms,
      profileImage,
      bio,
    );

      console.log('ZZZZZZ')
      
    if (!createdUser) {
      console.log('AAAA')
      const notCreated = new BadRequestEvent(
        req.user,
        EVENT_MESSAGES.badRequest,
        EVENT_MESSAGES.createUserFail
      );
      myEmitterErrors.emit('error', notCreated);
      return sendMessageResponse(res, notCreated.code, notCreated.message);
    }

    console.log('XX');
  } catch (err) {
    // Error
    const serverError = new RegistrationServerErrorEvent(
      `Register user Server error`
    );
    myEmitterErrors.emit('error', serverError);
    sendMessageResponse(res, serverError.code, serverError.message);
    throw err;
  }
};


// My reg user function in primsa
export const createUser = (
  lowerCaseEmail,
  hashedPassword,
  lowerCaseFirstName,
  lowerCaseLastName,
  lowerCaseCountry,
  lowerCaseCity,
  lowerCaseUsername,
  gender,
  dob,
  agreedToTerms,
  profileImage,
  bio
) =>
  dbClient.user.create({
    data: {
      email: lowerCaseEmail,
      password: hashedPassword,
      agreedToTerms: agreedToTerms,
      profile: {
        create: {
          firstName: lowerCaseFirstName,
          lastName: lowerCaseLastName,
          country: lowerCaseCountry,
          city: lowerCaseCity,
          gender: gender,
          dob: dob,
          profileImage: profileImage,
          bio: bio,
          username: lowerCaseUsername,
        }
      }
    },
  });

my terminal says this

Registering new user
ERROR EVENT RegistrationServerErrorEvent {
  user: 'Failed to register',
  topic: undefined,
  code: 500,
  message: 'Internal Server Error'
}
TTTTT RegistrationServerErrorEvent {
  user: 'Failed to register',
  topic: undefined,
  code: 500,
  message: 'Internal Server Error'
}
POST /users/register 500 1220.477 ms - 52
PrismaClientKnownRequestError:
Invalid `prisma.user.create()` invocation:


Unique constraint failed on the fields: (`username`)
    at pn.handleRequestError (C:UsersTomDocumentscodejavascriptworlds-smartest-frontendservernode_modules@prismaclientruntimelibrary.js:176:6477)
    at pn.handleAndLogRequestError (C:UsersTomDocumentscodejavascriptworlds-smartest-frontendservernode_modules@prismaclientruntimelibrary.js:176:5907)       
    at pn.request (C:UsersTomDocumentscodejavascriptworlds-smartest-frontendservernode_modules@prismaclientruntimelibrary.js:176:5786)
    at async t._request (C:UsersTomDocumentscodejavascriptworlds-smartest-frontendservernode_modules@prismaclientruntimelibrary.js:179:10484)
    at async registerNewUser (file:///C:/Users/Tom/Documents/code/javascript/worlds-smartest-frontend/server/src/controllers/users.js:168:25) {
  code: 'P2002',
  clientVersion: '4.13.0',
  meta: { target: [ 'username' ] }

So it doesnt want to finish my error even tho it prints out. But it wont follow my !created function

Im not sure what to do. I have not encounter this issue before.

addEventListener for ‘iframe’ and ‘input’ tag to extract the content

So I’m working on a Chrome extension that listens to input events inside the DOM and responds accordingly. I used my school website to work with. I noticed that all text content doesn’t have the same tags. Atm I’m stuck where I can access only {input txt} content by using this line of code event.target.value.includes('$nutshell') but to be able to access the content inside {iframe} document the line of code above doesn’t work but this event.target.textContent.includes('$nutshell') works.So I can access both contents by changing value to textContent and vice versa, but I’m trying to get both values simultaneously. I tried many things, including if else statements to check the (document.activeElement.tagName), but they don’t work. My problem exists in the content script, I’ll post my code and screenshots below for more clarity. Any help would be appreciated.


iframe
input


content.js

const nutshell = /$(nutshell|ns)s+([^;]+)s*;/;
const nutshell_s = /$nutshells+-ss+([^;]+)s*;/;

  document.addEventListener("input", function(event) {
    if (event.target.value.includes('$nutshell')) {
      const match_s = event.target.value.match(nutshell_s);
      const match = event.target.value.match(nutshell);
      if (match_s) {
        const command = match_s[1].trim();
        console.log(`Command: ${command}`);
        chrome.runtime.sendMessage({text: 'help_s',command: command }, function(response) {
        });
      } else if (match) {
        const command = match[1].trim();
        console.log(`Command: ${command}`);
        chrome.runtime.sendMessage({text: 'help',command: command }, function(response) {
  
        });
      }
      else {
        console.error('Extension context is invalid');
      }
    }
  });

manifest.json

{
  "name": "in-a-nutshell",
  "description": "Uses the ChatGPT API to provide assistance",
  "version": "1.0",
  "manifest_version": 2,
  "permissions": ["activeTab", "storage"],
  "content_scripts":[
    {
      "matches":["<all_urls>", "https://csufullerton.instructure.com/*"],
      "js": ["content.js"],
      "run_at": "document_end",
      "all_frames": true,
      "match_about_blank": true
    }
  ],
  "background":{
    "scripts": ["background.js"]
  },
  "browser_action": {
    "default_icon": "nutshell.png",
    "default_title": "In-a-Nutshell",
    "default_popup": "popup.html"
  }
}

Cube rotation formula

I need a formula that allows me to rotate a 3d object around a point, I’m creating a 3d renderer using a “Weak Perspective Projection” method to project the points onto a 2d screen, I create these objects using functions like newCube(x,y,z,size) and added them to an array of objects

heres the function i use for putting the points into the object:

function newCube(x, y, z, size,fill){
  object = {points:[[x-size,y-size,z-size],[x-size,y-size,z+size],
                    [x+size,y-size,z-size],[x-size,y+size,z-size],
                    [x-size,y+size,z+size],[x+size,y-size,z+size],
                    [x+size,y+size,z-size],[x+size,y+size,z+size]],
            vertices:[[0,1],[0,2],[0,3],
                      [2,5],[3,6],[3,4],
                      [4,7],[6,7],[7,5],
                      [5,1],[4,1],[2,6],
              ],
            rot:[0,0,0],
            origin:[x,y,z],
            type:"cube"
            fill:fill
  };
  objects.push(object);
}

I am using a for loop for every point in the object, should I be doing this or not?“

Trying to write a photoshop script to read csv variables

I need corrections on this photoshop script.

I can open the csv file but it cant swap out the images on the layers with the images (i used the path) on the csv file.

It can be achieved without script by using photoshop variables but i want to swap out lots of files and cant go back and forth clicking and repeating task.

`// Open the CSV file and parse its content
var csvFile = File.openDialog("Select CSV file", "*.csv");
csvFile.open("r");
var csvContent = csvFile.read();
csvFile.close();
var csvData = csvContent.split("n");

// Loop through the CSV data and replace images on each layer in Photoshop
for (var i = 1; i < csvData.length; i++) {
  var rowData = csvData[i].split(",");
  
  // Open the image file
  var imageFile = new File(rowData[0]);
  var docRef = app.open(imageFile);
  
  // Loop through each layer and replace the image
  for (var j = 1; j <= docRef.layers.length; j++) {
    var layer = docRef.layers[j - 1];
    
    // Check if the layer is a image layer
    if (layer.kind == LayerKind.NORMAL && layer.bounds.toString() != "[0,0,0,0]") {
      
      // Replace the image layer with the new image file
      var imageFilePath = rowData[j];
      var newLayer = docRef.artLayers.add();
      newLayer.move(layer, ElementPlacement.PLACEBEFORE);
      newLayer.name = layer.name;`your text`
      newLayer.kind = LayerKind.NORMAL;
      var imageFileRef = new File(imageFilePath);
      app.activeDocument.activeLayer = newLayer;
      app.load(new File(imageFilePath));
      docRef.selection.selectAll();
      docRef.selection.copy();
      docRef.selection.deselect();
      app.activeDocument.paste();
      layer.remove();
    }
  }

  // Save the modified image file
  var saveOptions = new JPEGSaveOptions();
  saveOptions.quality = 12;
  var newFilePath = rowData[0].replace(".jpg", "_modified.jpg");
  docRef.saveAs(new File(newFilePath), saveOptions, true, Extension.LOWERCASE);
  docRef.close(SaveOptions.DONOTSAVECHANGES);
}

alert("Done!");`

How to assign a HTML form element to a JavaScript global variable? [duplicate]

index.html file

<!DOCTYPE html> 
<html>
<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">
<script src="1script.js"></script>
<title>Document</title>
</head>

<body>
  <form id="form1" name="userInputForm"> 
   <label for="moq">MOQ:</label><br>
   <input type="number" id="moq" name="moq" onfocusout=""><br>
    <br>
    
    <div id="calculate"><input type="button" name="button" style="width: 8rem; height: 2rem;" value="Calulate"  onClick="priceResults()"></div>

</form>

</body>


</html>

scripts.js file

var userInputFormm = document.getElementById("form1");

 function priceResults(){
   alert(userInputFormm.moq.value);
  }

So what I am trying to do is access the form element into a global variable userInputFormm.
but this code gives me an error as shown below when I click Calculate. enter image description here

when I change it into a local variable to the function priceResults(), or access it directly using getElementBy in the function, it works perfectly like below.

scripts.js file

enter image description here

Results

enter image description here

I could have gone ahead to create the local variables, but I have a lot of functions to create and I cannot recreate these variables every time, it will make my codes more than I intend them to be.

What am I missing?

Node.js + Angular : Cors problem – fly.toml

I would need help with my deployment issue on “fly.io” platform. Communication between the frontend and backend is functional for a while, but then this error occurs:

“Acess to XMLHttpRequest at ‘https://todo-backend.fly.dev’ from origin ‘https://todo-frontend.fly.dev’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.”

where the problem is that I am not sending the header from the frontend to the backend, which was previously being sent and suddenly stopped. My application works fine until I transferred it to this platform. May I ask how someone else solved this issue?
My backend configuration is as follows:

app.use(
  cors({
    origin: [
      "https://todo-front.fly.dev",
    ],
    credentials: true,
  })
);

backend log:
enter image description here

And this is my frontend configuration:

httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': 'https://todo-frontend.fly.dev',
    }),
    responseType: 'text' as 'json',
    withCredentials: true,
  };

fly.toml frontend:

app = "todo-front"
kill_signal = "SIGINT"
kill_timeout = 5
processes = []

[env]

[experimental]
  allowed_public_ports = []
  auto_rollback = true

[[services]]
  http_checks = []
  internal_port = 8080
  processes = ["app"]
  protocol = "tcp"
  script_checks = []
  [services.concurrency]
    hard_limit = 25
    soft_limit = 20
    type = "connections"

  [[services.ports]]
    force_https = true
    handlers = ["http"]
    port = 80

  [[services.ports]]
    handlers = ["tls", "http"]
    port = 443

  [[services.tcp_checks]]
    grace_period = "1s"
    interval = "15s"
    restart_limit = 0
    timeout = "2s"

fly.toml backend:

app = "todo-back"
kill_signal = "SIGINT"
kill_timeout = 5
processes = []

[env]
  ALLOWED_ORIGINS = "https://todo-frontend.fly.dev"
[experimental]
  allowed_public_ports = []
  auto_rollback = true

[[services]]
  http_checks = []
  internal_port = 3000
  processes = ["app"]
  protocol = "tcp"
  script_checks = []
  [services.concurrency]
    hard_limit = 25
    soft_limit = 20
    type = "connections"

  [[services.ports]]
    force_https = true
    handlers = ["http"]
    port = 80

  [[services.ports]]
    handlers = ["tls", "http"]
    port = 443

  [[services.tcp_checks]]
    grace_period = "1s"
    interval = "15s"
    restart_limit = 0
    timeout = "2s"

Thank you in advance

I have tried to change ‘Access-Control-Allow-Origin’: ‘https://todo-frontend.fly.dev’ to
‘Access-Control-Allow-Origin’: ‘*’ etc. nothing works. Is it problem of the hosting?

Difference in ReferenceError in a block scope and global scope if a let variable is used before initialization

What’s the reason for different ReferenceErrors for these two snippets?

{
    console.log(a);
    let a;
}

ReferenceError: Cannot access ‘a’ before initialization

console.log(a);
let a;

ReferenceError: a is not defined

Same Errors are thrown if the variable is declared using const a=5;.

Also, errors vary depending on which side of the assignment operator a has been used.

a=5;
let a;

ReferenceError: Cannot access ‘a’ before initialization

var b=a;
let a;

ReferenceError: a is not defined

I read through the scope related docs on MDN but couldn’t come up with an explanation.

How to use ref to run function from parent in multiple child components using vue.js

Im trying to run a function in each of my child components using ref, however it seems to do nothing when i run it.

Each of the child components is based upon data from an API. When call updateUserDataDB
it fetches said api, uploads to firestore and changes it owns variables. However currently this has to be done via a button on each child component. I would like to setup a button on the parent component to run this function on all children. For this i have looked at this article which was linked in another question, however to avail. Perhapds is has something to do with using the same ref in all children? Any help or tips is appreciated.
My code looks as such

App.vue (parent)

<template>
<body>
  <button class="btn-right"  @click ="updateUserDataDB"> Update all PlayerBoxes</button>
  <p v-for="country in countries" :key="country">
    <PlayerBox :players="country" ref="refresh_db"/>
  </p>
</body>
</template>
<script>

import { query, collection, getDocs, orderBy, setDoc, doc } from "firebase/firestore"
import db from './firebase/init.js'
import PlayerBox from './components/PlayerBox.vue'
import{ref} from "vue"

export default {
  name: 'App',
  components: { PlayerBox},
  data() {
    return {
      players: [],
    }
  },
  created() {
    this.getPlayerFirestore()
    
  },
  methods: {
    updateUserDataDB(){
      console.log("clicked")
      this.$refs.refresh_db.updateUserDataDB()
    },
    async getPlayerFirestore() {
      // query to get all docs in 'users' collection
      const q = query(collection(db, 'users'), orderBy('elo', 'desc'));
      const querySnap = await getDocs(q);
      // add each doc to 'players' array 
      querySnap.forEach((doc) => {
        this.players.push(doc.data())        
      })
    },
</script>

PlayerBox.vue (child)

<template>
...
</template>
<cript>

import { getDoc, updateDoc , doc} from "firebase/firestore"
import db from '../firebase/init.js'
import {ref} from "vue";

export default ({
    props:["players"],
    data(){
    ...},
    methods: {
        async updateChampionStats(){
           ...
        },
        async updateUserDataDB() {
        },
    }
})

starting an event when scrolling past an ID

I found this ajvaScript buit that reduces the height of a div, but i need it to start after the user scrolls past an ID, how can i add this to trigger after a certain paoint?

this is the original script:

console.clear();

const div = document.querySelector('scrollthing');

window.addEventListener('scroll', () => {
console.log(window.scrollX)
scrollthing.style.height = `${400 - window.scrollY}px`;
});

something like combining it with this :

window.addEventListener("scroll", function() {
var elementTarget = document.getElementById("section-2");
if (window.scrollY > (elementTarget.offsetTop + elementTarget.offsetHeight)) {
alert("You've scrolled past the second div");
}
});

but instead of teh alert ot should changethe height

it works now but it start upon scrolling off the top which is too early if teh div is below the fold

maplibre/mapbox gl animated glsl shader at specific map coordinates using javascript

I have these two glsl shader examples:
https://developers.arcgis.com/javascript/latest/sample-code/custom-gl-visuals/
and
https://www.shadertoy.com/view/3djSDD, the first one actually being on an arcgis map and the second just being a link to another “ping” on the shadertoy website.

I am trying to take the glsl shader from either of these and implement it into my own maplibre map (which is different from the arcgis example).

I am currently able to use a very basic glsl shader which draws a triangle at specific coordinates but I’m a complete GLSL novice and don’t know exactly how to adjust the glsl and javascript code to make it work.

Here’s what I have (locally) that draws the square:
https://maplibre.org/maplibre-gl-js-docs/example/custom-style-layer/

I should be able to simply draw the “ping” glsl shader at a location like:

lng: 25.004,
lat: 60.239

… but I’m not sure how to modify the array buffer(s) to make it actually draw the “ping”

“User” is not a constructor in a class

User is not a constructor when i declare it in the top of the file

const User = require('./User')
module.exports = class DmChannel {
    /**
     * 
     * @param {Client} client
     * @param {*} data 
     */
    constructor(client, data) {
        /**
     * The client that instantiated this
     * @name Base#client
     * @type {Client}
     * @readonly
     */
        Object.defineProperty(this, 'client', { value: client })

        this.id = data.id
        this.last_message_id = data.last_message_id
        this.type = data.type
        this.name = data.name
        this.flags = data.flags
        this.createdTimestamp = Utils.getTimestampFrom(this.id)
        this.createdAt = new Date(this.createdTimestamp)
        this.user = data.user || data.recipients ? data.recipients.length < 1 ? null : new User(client, data.recipients[0]) : null
        this.data_is_available = true
    }
}

Someone can explain me why “User” is not a constructor is rejected ?
This one will work :
I require the class User just above the line where I need it

module.exports = class DmChannel {
    /**
     * 
     * @param {Client} client
     * @param {*} data 
     */
    constructor(client, data) {
        /**
     * The client that instantiated this
     * @name Base#client
     * @type {Client}
     * @readonly
     */
        Object.defineProperty(this, 'client', { value: client })

        this.id = data.id
        this.last_message_id = data.last_message_id
        this.type = data.type
        this.name = data.name
        this.flags = data.flags
        this.createdTimestamp = Utils.getTimestampFrom(this.id)
        this.createdAt = new Date(this.createdTimestamp)
        const User = require('./User')
        this.user = data.user || data.recipients ? data.recipients.length < 1 ? null : new User(client, data.recipients[0]) : null
        this.data_is_available = true
    }
}

Thanks !