How to make javascript change event trigger on a hidden file input button

I am generating a content in “order summary” modal using javascript. As part of the table I want to give a user an option of either generate a order confirmation pdf or attach that pdf from local storage. The attachment function is through a hidden input-type button, that is called using a visible and specifically styled submit button

summaryContainer.innerHTML = '';
for (const [supplierId, group] of supplierGroups) {
    const supplierDiv = document.createElement('div');
    supplierDiv.className = 'supplier-summary-table';
    
    let supplierHtml = `
        <h6>Supplier: ${group.supplier.supplierName}</h6>
    `;

    

    // Add order confirmation section
    supplierHtml += `
        <div class="po-upload-section">
            <div>
                <h6 class="mb-1">Purchase Order</h6>
            </div>
            <div class="po-actions">
                <button class="btn btn-outline-primary generate-po-btn" data-supplier-id="${supplierId}">
                    <i class="bi bi-file-earmark-plus"></i> Generate PO
                </button>
                or
                <div class="upload-po" id="upload-po-container-${supplierId}">
                    <!-- Here I insert the file input function -->
                </div>
            </div>
            <div id="po-status-${supplierId}" class="mt-3"></div>
        </div>
    `;
    
    supplierDiv.innerHTML = supplierHtml;
    summaryContainer.appendChild(supplierDiv);

    // Create and attach file input programmatically
    const uploadContainer = supplierDiv.querySelector(`#upload-po-container-${supplierId}`);
    const uploadButton = document.createElement('button');
    uploadButton.className = 'btn btn-outline-secondary';
    uploadButton.innerHTML = '<i class="bi bi-upload"></i> Attach PO';

    const fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.accept = '.pdf';
    // fileInput.className = 'form-control';
    fileInput.id = `po-upload-${supplierId}`;
    fileInput.dataset.supplierId = supplierId;

    uploadContainer.appendChild(fileInput);
    uploadContainer.appendChild(uploadButton);

    fileInput.addEventListener('change', function(e) {
        console.log("change event triggered");
    }, false);

    uploadButton.onclick = (e) => {
        e.preventDefault();
        fileInput.value = ''; // Reset value to ensure change event
        fileInput.click();
    };

    // Change the style to make it invisible
    fileInput.style.opacity = '0';
            
}

The page renders correctly and when pressing the Attach PO button, file explorer window opens to select the correct file. However, when the file is selected and confirmed, the change event is not triggered, I see no logs in the console related to that. The button also somewhat freezes – clicking it the second time doesn’t open file explorer window.
I am testing this in Firefox 134.0 running in Ubuntu 22.04.

Edit
I forgot to add that searching here hints towards two main reasons that could be the cause for this:

  1. change event not triggering because an identical file is selected as is the case here, or
  2. element getting deleted, so appendChild should be included to make sure the element is persistent, as is here

In my case, the issue persists even if the input button is clicked for the first time and I indeed have already tried adding appendChil, but to no avail.

recommend better way to handle Repeat block javascript

I have block of code which I repeat in alot place in the program. and cannot make it into function or class .

is there a method where I can write a bunch of blocks javascript on external file and in main program I can point to which javascript file and block .

this way when I need to modify code, I no need to hunt whole program

How to import SASS file as inlined CSS (not JS) in SvelteKit/Vite

How can I import a SASS file as inlined CSS (not JS) using SvelteKit and/or Vite?

The SASS file is imported in +page.svelte:

<script lang="ts">
    import '../app.scss';
</script>

The SASS file itself is a simple configuration of PicoCSS:

@use '@picocss/pico/scss/pico' with (
    $theme-color: 'zinc'
);

Full minimal repo:


The reason I wish to do this is to avoid an FOUC.

  • There is a moment where a white background is flashed until the CSS for dark mode (compiled to JS) is loaded.
  • (More noticeable on mobile iOS, but apparent in Chrome when devtools set to “disable cache” and “throttle to 3G.” Or when JS is simply disabled.)
  • Although SvelteKit SSR will inline the CSS, this is not an option for SPAs.

I was able to avoid the FOUC by manually copying the relevant Pico CSS for dark mode to the base app.html Svelte template, but I’m looking for a more comprehensive and automatic solution.

I think this answer may be related, but I’m not sure how to configure Vite like this in the context of a SvelteKit project: https://stackoverflow.com/a/78249321/117030

Create Object with Name & Value of specific localstorage

Found this code on the net:

const keys=Object.keys(localStorage).filter(key=>key.includes('doinclude'));
const todos=keys.map(key=>JSON.parse(localStorage.getItem(key)));

The resulting ‘todo’ is an object holding the localstorage values.

What to change in the above code to include both name and value of each localStorage entry?

How to resolve issues with renaming `index.html` to `vite.index.html` in Vite?

I am using Vite (without any frameworks) and have the following folder structure:

src/
  main.js
index.html
vite.config.js

I want to rename index.html to vite.index.html. To achieve this, I used the solution from this Stack Overflow question and updated my vite.config.js as follows:

export default {
  base: "/admin",
  build: {
    rollupOptions: {
      input: {
        app: './vite.index.html',
      },
    },
  },
  server: {
    open: '/vite.index.html',
  },
};

After making these changes, I encountered two issues:

  1. The build output generates vite.index.html in the dist folder, but I need it to be index.html.
  2. When I open the browser, I get this error:
    The server is configured with a public base URL of /admin - did you mean to visit /admin/vite.index.html instead?
    

    This is caused by the base being set to /admin, which is necessary for my setup.

How can I resolve these issues?

Three.js issues with models (Rotating them whilst they are in the scene)

import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';

const canvas = document.querySelector('#frontPageCanvas');
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth 
window.innerHeight, 0.1, 1000);

const renderer = new THREE.WebGLRenderer({canvas, antialias: true});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor( 0xffffff, 0);


function loadFiles(capsulesFiles, scene) {

  const capsuleloader = new GLTFLoader();

  capsulesFiles.forEach((capsulesFile) => {
    capsuleloader.load(capsulesFile, (gltf) => {
      scene.add(gltf.scene);
    });
  });
 };

let capsulesFiles = ['../three.js/models/capsule_1.glb',  
'../three.js/models/capsule_1.glb'];
loadFiles(capsulesFiles, scene);


//const geometry = new THREE.BoxGeometry(2, 2, 2);
//const material = new THREE.MeshBasicMaterial({color: 0x0000ff});
//const cube = new THREE.Mesh(geometry, material);
//scene.add(cube);

camera.position.z = 5;

console.log(scene);

function animate()  {
    requestAnimationFrame(animate);
//    cube.rotation.x += 0.05
//    cube.rotation.y += 0.05
    scene.children[0].rotation.y += 0.05;
    scene.children[1].rotation.x -= 0.01;
    scene.children[1].rotation.y -= 0.01;

    renderer.render(scene, camera);
}

animate();

Hi, I am new to Three.js and JavaScript! I was trying to see if I could insert my glb models via array (to save code time instead of having unique functions for each one). I figured I could use the scene object to do this, but when I run this code I get this error for the rotation code which says Uncaught TypeError: Cannot read properties of undefined (reading 'rotation') at animate (threejsanimations.js:49:23) at threejsanimations.js:56:1

However, after a little delay, one of my models does rotate (makes no sense since all rotation code shouldn’t work). Not sure how to fix this. Also, if any additional help as to why my models have no texture/material would be cool (I used Maya to make them with aiStandardSurface of Glass and Plastic for the materials and the Verge3D plugin to export them as .glb files).

Why do _id and _owner auto-fill in Wix with Google Cloud SQL, but _createdDate and _updatedDate do not?

I’m using Google Cloud SQL (Postgres) as an external database connected to Wix. When I insert a row via bulkInsert, the _id and _owner fields are automatically populated. However, _createdDate and _updatedDate remain empty unless I manually set them.

According to Wix, these fields are required for read-write access, but there’s no clear guidance on if these field also automatically get populated.

Example table structure:

CREATE TABLE example_table (
  _id UUID DEFAULT gen_random_uuid(),
  _owner VARCHAR(255),
  _createdDate TIMESTAMP,
  _updatedDate TIMESTAMP
);

Should I use DEFAULT now() or a trigger or should wix populate them? What is the standard practice for timestamps in this setup related to WIX.

Why does .splice remove the same item from a different Object Array?

I have 2 variables that store an Object one of the Object’s properties is another Object (Array).

const master = [
        {key:"Apprentices", label:"Apprentices", children:[
            {key:"1", label:"Linda"},
            {key:"2", label:"George"}
        ]},
        {key:"Electricians", label:"Electricians", children:[
            {key:"3", label:"Kate"},
            {key:"4", label:"Diane"}
        ]}
    ]
var elements = Array.from(master);

I want to remove {key:"4", label:"Diane"} from the elements variable (using .splice), but when I do it also removes it from the master variable.

Interestingly, if I remove a non child property e.g.

{key:"Apprentices", label:"Apprentices", children:[
                {key:"1", label:"Linda"},
                {key:"2", label:"George"}
            ]}

it doesn’t remove it from the master variable, just the elements variable as intended.

In my application I can’t have the master variable as a CONST unfortunately, but on jsplayground.dev I can and it doesn’t make a difference.


Here is my full code for removing an item from within the children property that ends up removing from both variables:

const master = [
        {key:"Apprentices", label:"Apprentices", children:[
            {key:"1", label:"Linda"},
            {key:"2", label:"George"}
        ]},
        {key:"Electricians", label:"Electricians", children:[
            {key:"3", label:"Kate"},
            {key:"4", label:"Diane"}
        ]}
    ]
var elements = Array.from(master);
var el = {'name': 3, 'label': 'Kate'}

console.log(elements)
console.log(master) // this is master variable not 'elements' variable

function addRemoveElement(el, addRemove, all) {
  if (addRemove === 0) {
    // remove
    elements.forEach((item) => item.children.forEach((subItem, i) => {
      if (subItem.label === el.label) {
        item.children.splice(i, 1);
      }
    }));
  }

console.log(elements)
console.log(master) // this is master variable not 'elements' variable
}

addRemoveElement(el, 0)

Here is my full code for removing an top level property that correctly removes from just one variable:

const master = [
        {key:"Apprentices", label:"Apprentices", children:[
            {key:"1", label:"Linda"},
            {key:"2", label:"George"}
        ]},
        {key:"Electricians", label:"Electricians", children:[
            {key:"3", label:"Kate"},
            {key:"4", label:"Diane"}
        ]}
    ]
var elements = Array.from(master);
var el = {'key': 'Apprentices', 'label': 'Apprentices'}

console.log(elements)
console.log(master) // this is master variable not 'elements' variable

function addRemoveElement(el, addRemove, all) {
  if (addRemove === 0) {
    // remove
    elements.forEach((item, i) => {
      if (item.label === el.label) {
        elements.splice(i, 1);
      }
    });
  }

console.log(elements)
console.log(master) // this is master variable not 'elements' variable
}

addRemoveElement(el, 0)

Console logs for each:

1 – removes from both:

(2) [Object, Object]
0: Object
1: Object
key: "Electricians"
label: "Electricians"
children: (2) [Object, Object]

(2) [Object, Object]
0: Object
1: Object
key: "Electricians"
label: "Electricians"
children: (2) [Object, Object]

(2) [Object, Object]
0: Object
1: Object
key: "Electricians"
label: "Electricians"
children: (1) [Object]

(2) [Object, Object]
0: Object
1: Object
key: "Electricians"
label: "Electricians"
children: (1) [Object]

2 – correctly removes from one

(2) [Object, Object]
0: Object
1: Object

(2) [Object, Object]
0: Object
1: Object

(1) [Object]
0: Object

(2) [Object, Object]
0: Object
1: Object

I’m new to JavaScript and I’ve been stung before when 2 variables are populated from the same source and if that source changes both variables do also. But in this case it shouldn’t happen because of Array.from() and also CONST, but my second example doesn’t remove from both.

I’m really stuck with this, so any guidance would be greatly appreciated. Thank you.

Wix bulkInsert not inserting 0 or false values into Google Cloud SQL (Postgres)

I’m using wixData.bulkInsert to insert records into a Google Cloud SQL (Postgres) database. The issue is that numeric 0 and false values are not being saved, even though they are present in the final object sent to the bulkInsert method.

Here’s an example object:

{
  "product_id": "442667902",
  "delivery_rate": 0,
  "is_black_listed": false
}

In the database, delivery_rate and is_black_listed become NULL. Why does this happen, and how can I ensure 0 and false are inserted correctly?

Is this due to Wix or SQL, and how can I fix it?

CORS Issue: Electron App Fails to Access API on Localhost and Cloud Functions

I’m working on an Electron app hosted on http://localhost:1212, and it needs to make API requests to either of the following:

  1. Localhost API: http://localhost:5001/nft-discord-relay/us-central1/api/farmer/validate
  2. Cloud Function: https://us-central1-nft-discord-relay.cloudfunctions.net/api/farmer/validate

However, I’m consistently getting a CORS error when attempting to make a POST request:

Access to fetch at ‘http://localhost:5001/nft-discord-relay/us-central1/api/farmer/validate’ from origin ‘http://localhost:1212/’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

Here’s the relevant setup:


Electron App Code

This is how I send the request:

export async function validateFarmer(discordId, farmerCode, walletAddress) {
    try {
        const response = await fetch(`${API_BASE_URL}/farmer/validate`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                discordId,
                farmerCode,
                walletAddress,
            }),
        });

        const data = await response.json();
        return data;
    } catch (error) {
        console.error(error);
        return {
            isValid: false,
            message: 'Failed to connect to the server',
        };
    }
}

API Server Code

I use Express and cors middleware to handle CORS. Here’s the relevant code:


CORS Middleware

const cors = require('cors');

const corsMiddleware = cors({
    origin: (origin, callback) => {
        const allowedOrigins = [
            'http://localhost:1212',
            'https://us-central1-nft-discord-relay.cloudfunctions.net',
        ];
        if (!origin) return callback(null, true); // Allow requests with no origin (e.g., mobile apps)
        if (allowedOrigins.includes(origin)) {
            callback(null, true);
        } else {
            callback(new Error('Not allowed by CORS'));
        }
    },
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization'],
    credentials: true,
    maxAge: 86400, // Cache preflight requests for 24 hours
});

module.exports = corsMiddleware;

Router:

const express = require('express');
const router = express.Router();
const corsMiddleware = require('./path-to-cors-middleware'); // Adjust the path accordingly

router.use(corsMiddleware);

router.post('/farmer/validate', async (req, res) => {
    console.info('Validate request received', {
        discordId: req.body.discordId,
        walletAddress: req.body.walletAddress,
    });

    const { discordId, farmerCode, walletAddress } = req.body;
    if (!discordId || !farmerCode || !walletAddress) {
        console.error('→ Missing required fields');
        return res.status(400).json({
            success: false,
            message: 'Discord ID, Farmer Code, and Wallet Address are required',
        });
    }

    const result = await FarmerHelper.validateFarmer(
        discordId,
        farmerCode,
        walletAddress
    );
    console.info('→ Validation complete', {
        discordId,
        isValid: result.isValid,
    });

    res.status(result.isValid ? 200 : 400).json(result);
});

module.exports = router;

getStream Chat custom Message Actions

Following what their doc on https://getstream.io/chat/docs/sdk/angular/components/MessageActionsBoxComponent/ to add my own custom message action but didn’t seem to work, hoping someone can help me out

import {
  StreamMessage,
  CustomMessageActionItem,
  DefaultStreamChatGenerics
} from "stream-chat-angular";

customActions: CustomMessageActionItem<DefaultStreamChatGenerics>[] = [
    {
      actionName: 'custom-action',
      actionLabelOrTranslationKey: 'Custom Action',
      actionHandler: (message: StreamMessage<DefaultStreamChatGenerics>) => {
        console.log('Custom action executed for:', message);
      },
      isVisible: (enabledActions: string[]) => {
        return enabledActions.includes('custom-action');
      },
    }
  ];

ngAfterViewInit(): void {
  this.messageActionsService.customActions$.next(this.customActions);
}

Why closure use much more memory than plain JS object?

Run these two code in Node.js:

const list = Array(1e6).fill(0).map((_, i) => i);
const obj_list = list.map(v => ({ v }));
console.log(process.memoryUsage());
// {
//   rss: 130670592,
//   heapTotal: 86892544,
//   heapUsed: 54635152,
//   external: 1019787,
//   arrayBuffers: 16858
// }
const list = Array(1e6).fill(0).map((_, i) => i);
const fun_list = list.map(v => () => v);
console.log(process.memoryUsage());
// {
//   rss: 189992960,
//   heapTotal: 152428544,
//   heapUsed: 117480576,
//   external: 1019787,
//   arrayBuffers: 16858
// }

Running a proxy on express, running into problems using it on the browser

I’m attempting to run a proxy middleware on express to proxy any requests to my localhost:5000 to the target url. I’m using a free trial residential proxy for the proxy agent, and the initial request seems to be being proxied just fine – the issue is none of the pages can load any javascript/assets/api. This is what it would look like, using Reddit as an example:

I navigate to localhost:5000 on my browser
It takes me to https://www.reddit.com, page looks messed up and only html is rendered
I open browser console, tons of errors about Axios (Reddit api getting confused?)
This is the relevant code:

const url = 'https://www.reddit.com/';
const proxyAgent = new HttpsProxyAgent(
        `https://${proxy_username}:${proxy_password}@${proxy_host}:${proxy_port}`,
    );

const proxyMiddleware = createProxyMiddleware({
    cookieDomainRewrite: {
        '*': '',
    },
    target: url,
    changeOrigin: true,
    ws: true,
    agent: proxyAgent,
    autoRewrite: true,
    pathRewrite: {
        '^/': '/',
    },
    on: {
        proxyRes: function (
            proxyRes: http.IncomingMessage,
            req: http.IncomingMessage,
            res: http.ServerResponse,
        ) {
            proxyRes.headers['Access-Control-Allow-Origin'] = '*';
            proxyRes.headers['Access-Control-Allow-Credentials'] = 'true';
            proxyRes.headers['Content-Security-Policy'] = 'upgrade-insecure-requests';
            if (proxyRes.headers.location) {
                proxyRes.headers.location = proxyRes.headers.location.replace(
                    url,
                    `http://localhost:${port}`,
                );
            }
        },
    },
});

removing layer that created by an ajax array from leaflet map

I have an array consisting of coordinates and variables that I want to plot in the map using Ajax. Everything works properly to show the marker, but it will not remove the layer, and still show the next batch operation(nothing error shows).

var marker1;
var marker2;
var visible;
var nonvisible; 

$(function () {
         $('input.leaflet-control-findspot').on('click', _findtheSPot);
     });



_findtheSPot = function () {

   /////////i still figure out this code below to remove the marker,nothing error showed////////
            if (mymap.hasLayer(visible)) {
                mymap.removeLayer(visible);

            }
            if (mymap.hasLayer(nonvisible)) {
                mymap.removeLayer(nonvisible);
            }
            var visible = L.layerGroup().addTo(mymap);
            var nonvisible = L.layerGroup().addTo(mymap);
   /////////i still figure out this code above to remove the marker,nothing error showed////////

$.ajax({
                type: "POST",
                data: {
                    arrayraw: solararray,
                    lat: objlat,
                    long: objlng,
                    objheight: document.getElementById('leaflet-control-inputOheight').value
                },
                cache: false,
                url: "php/ujicoba.php",
                dataType: "json",
                beforeSend: function () {
                    $("#route-loading").show();

                },
                success: function (data) {

                    $("#route-loading").hide();
   /////////this code uses an array to show the marker in the map////////
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].ket == "visible") {
                            L.marker([data[i].lat, data[i].long], { icon: L.icon(icontargetMarker1) }).addTo(visible);
                           
                        } else {    
                            

                            L.marker([data[i].lat, data[i].long], { icon: L.icon(icontargetMarker2) }).addTo(nonvisible);
                        } 
   /////////this code uses an array to show the marker in the map////////
                    }

                }
                ,
                error: function () {
                    $("#route-loading").hide();
                    alert('Failed to get server respond');
                }

            });

my second attempt used this code to remove the marker

            if (mymap.hasLayer(visible)) {
                mymap.clearLayers();
                visible.clearLayers();
            }
            if (mymap.hasLayer(nonvisible)) {
                mymap.clearLayers();
                nonvisible.clearLayers();
            }

I hope somebody can figure out or have an idea for this problem it is my 5 days looking for the solution.

When creating a library, how do i know if a project installing some package?

I just create two library (Theme and Snackbar), those library can be install as a standalone package, but now I want to optionally support some feature in case a project installing two of my library.

for example

App.js

import { SnackbarProvider } from 'myLibrary/snackbar';
import { ThemeProvider } from 'myLibrary/theme';
import React from 'react';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import Routes from './Routes';

const App = () => {
  return (
    <SafeAreaProvider>
      <ThemeProvider color={primary:'red'}>
        <SnackbarProvider>
          <Routes />
        </SnackbarProvider>
      </ThemeProvider>
    </SafeAreaProvider>
  );
};

App.displayName = 'App';

export default App;

above code represent a project code that use both of my library (myLibrary/snackbar and myLibrary/theme)

and to access the theme within the project I’ve provided a hook called useTheme.

and now I want to enhanced myLibrary/snackbar library to reference myLibrary/theme setup like a color, font, etc.

How do i conditionally use useTheme within myLibrary/snackbar?

Snackbar.js

import React from 'react';
import {View,  Text} from 'react-native';
// import { useTheme } from 'myLibrary/theme';

const Snackbar = props => {
  // use color from `useTheme` or fallback to default color
  // conditionally use hook if exist
  // const {color} = useTheme()

  return (
    <View style={{flex: 1}}>
      <Text style={{
        color: color
      }}>Snackbar Component</Text>
    </View>
  );
};

export default Snackbar;