How to change the background color of an element in the most efficient way?

I have this square that I would like to change the background color of using buttons.

https://jsfiddle.net/jagupnvc/

<div id="square"></div>
<div>
  <button onclick="colorRed()">Red</button>
  <button onclick="colorYellow()">Yellow</button>
  <button onclick="colorBlue()">Blue</button>
</div>
#square {
  height: 200px;
  width: 200px;
  border: 1px solid black;
}

I’ve had a few thoughts on how I could do this, but I’d love some input on what would/wouldn’t work and how/why.

I do NOT want to implement a “Next” button that uses a loop to cycle through the colors, I would like a button for each color.

The first idea I had would be to make a separate function to change the color for each and every button. Keeping in mind that I’d like to do a dress-up game someday with a ton of different layers/outfit options, this doesn’t seem ideal or efficient and I really hope this is not the solution.

The second idea I had would be to somehow make an array of html buttons, an array of css colors classes, and somehow make a function that would link the two somehow? For example, if button1 gets pressed, show .color1, if button2 gets pressed, show .color2, etc.

Can’t style Google Maps autocomplete inputs – Shadow DOM issue

I’m struggling with Google’s new <gmp-place-autocomplete> web components. My dark-themed site looks terrible with these WHITE input boxes that can’t be styled.

The issue: Shadow DOM encapsulation prevents styling the actual input field (only dropdown parts are stylable via ::part() selectors).

I’ve tried:

  • High specificity CSS
  • !important flags
  • CSS variables
  • Custom overlays

Has anyone:
enter image description here

  1. Discovered any decent workaround to keep having the auto complete funtionality and find places by name in the search results?

enter image description here– any help appreciated!

What’s the mime type for photoshop in windows?

I have an upload text field that accepts the following mime types. Unfortunately, it doesn’t accept PSD and AI files on Windows computer but does on Mac. Does PSD and AI files have a different mime type on Windows computers?

".jpg",
".jpeg",
".png",
"image/jpeg",
"image/png",
"image/svg+xml",
"image/x-photoshop",
"image/vnd.adobe.photoshop",
".ai",
"application/vnd.adobe.illustrator",
"application/postscript",
"application/vnd.adobe.photoshop",
"application/x-photoshop"

How can I check for PSD and AI files on Windows in a safe way?

How can I calculate the average amount spent per customer from an array of purchase objects in JavaScript?

I’m trying to calculate the average amount each customer has spent based on an array of purchase objects. Here’s the sample data:

const purchases = [
  { customer: "Alice", amount: 250 },
  { customer: "Bob", amount: 400 },
  { customer: "Alice", amount: 150 },
  { customer: "David", amount: 300 },
  { customer: "Bob", amount: 200 },
  { customer: "Charlie", amount: 100 },
  { customer: "David", amount: 100 }
];

Here’s what I have tried so far:

function averageAmountSpent(arr) {
  const result = {};
  arr.forEach(item => {
    const customer = item.customer;
    result[customer] = (result[customer] || 0) + item.amount;
  });

  const average = {};
  for (const amount in result) {
    if (result.hasOwnProperty(amount) && typeof amount === 'number') {
      average[amount] = result[amount] / 2; // Not sure what to divide by
    }
  }

  return average;
}

console.log(averageAmountSpent(purchases));

This gives me the total amount spent per customer, but I’m not sure how to calculate the average amount spent by each customer (i.e., total spent divided by number of times they made a purchase). How should I modify this code to return each customer along with their average spend?

What I’ve tried:

  • I successfully grouped totals by customer.
  • I don’t know how to count how many times each customer appears in the
    array to compute the average.

What I want:

An object like this:

{
  Alice: 200,
  Bob: 300,
  David: 200,
  Charlie: 100
}

Each value should be the average of all amounts for that customer.

Any help or suggestions would be appreciated. Thanks!

Why is /* or * not working in my JavaScript express code?

app.get("/about", (req, res) => {
  res.send("you are in about path");
});

app.get("*", (req, res) => {
  res.send("you are in a path that doesn't exist");
});

I’m new (learnig) to this express.
Here /about is working but * or /* is throwing error. (But it works in the YouTube video)

Error: node_modulespath-to-RegExpdistindex.js:73
     throw new TypeError (`Missing parameter name at ${i}: ${DEBUG_URL}`);
     ^

TypeError: Missing parameter name at 1: https://git.new/pathToRegexpError

I have already tried

app.all("*", (req, res) => {
  res.status(404).send("you are in a path that doesn't exist");
});

and some more but nothing works.
I need to send response for all other paths/routes. That this path doesn’t exist.

Is there a way to force browsers to NOT preventDefault when adding an event listener to a submit button?

I have a test code like this:

<html>

<body>

</html>
<form method='get' action='https://www.duckduckgo.com/'>
  <button id='123' type='submit'>test</button>
  <script>
    const button = document.getElementById('123');
    button.addEventListener('click', (event) => {
      button.setAttribute('disabled', 'disabled');
      return true;
    }, true);
  </script>
</form>
</body>

</html>

The intention is that the button gets disabled, but then the event is propagated upwards and the form is still submitted. It works perfectly in SeaMonkey, but something prevents the default form submission in Firefox, Chrome, and (according to comments) Safari.

How do I make the form submit (i.e., not do event.preventDefault()) unless I specifically instruct it to? Is there event.doNotPreventDefault()?

Is there a way to force Chrome based browsers to NOT preventDefault when adding an event listener to a submit button?

I have a test code like this:

<html>

<body>

</html>
<form method='get' action='https://www.duckduckgo.com/'>
  <button id='123' type='submit'>test</button>
  <script>
    const button = document.getElementById('123');
    button.addEventListener('click', (event) => {
      button.setAttribute('disabled', 'disabled');
    });
  </script>
</form>
</body>

</html>

In all the browsers it seems to work, but in Chrome based browsers after disabling the button the form is not submitted. I have tried returning true from the function, adding the event to start during the propagation phase rather than bubbling up phase, but nothing seems to work in Chrome.

Is it a bug that i am dealing with, or is it a known behaviour? And most importantly, how do i make the form submit (i.e. not do event.preventDefault()) unless i specifically instruct it to? Is there event.doNotPreventDefault()?

JavaScript fetch doesn’t work with my php api [closed]

I have this JavaScript function where I want to fetch a get request to my php api.

    <script>
        function betoltSzamlak(palyazatId){
            if(palyazatId===""){
                document.getElementById("szamlaTable").innerHTML = "";
                return;
            }

            fetch("szamlak_api.php?palyazatId=" + palyazatId)
            .then(Response => Response.json())
            .then(adatok => {
                    let html = "<table class='table table-bordered'><thead><tr><th>Számlaszám</th><th>Dátum</th><th>Érték</th><th>Költség megnevezése</th></tr></thead><tbody>";
                    for (let sor of adatok) {
                        html += `<tr>
                                    <td>${sor.szamlaszam}</td>
                                    <td>${sor.datum}</td>
                                    <td>${sor.ertek}</td>
                                    <td>${sor.megnevezes}</td>
                                </tr>`;
                    }
                    html += "</tbody></table>";
                    document.getElementById("szamlaTable").innerHTML = html;
            })
            .catch(error => {
                document.getElementById("szamlaTable").innerHTML = "Hiba a lekérdezés során!";
            });
        }
    </script>

And this is where i want to use the fetched data.

        <form>
            <select onchange="betoltSzamlak(this.value)">
                <option value="">-- Válasszon pályázatot --</option>
                <?php
                    $palyazatok = json_decode(file_get_contents("http://localhost/otthoni_php_gyak/Feladatok/2025-05-11/Megoldasok/Web/www/palyazatok_api.php"));
                    foreach($palyazatok as $palyazat){
                        $id = htmlspecialchars($palyazat['id']);
                        $ta = htmlspecialchars($palyazat['tervezetA']);
                        $tc = htmlspecialchars($palyazat['tervezetC']);
                        echo "<option value='$id'>$id - $ta - $tc</option>";
                    }
                ?>
            </select>
        </form>
        <div id="szamlaTable"></div>

I tried to create a select where If I pick a value the value gets send to my php API which returns an sql query in JSON form which then I can display as a table.

As some of you suggested I’ll add some context to my question. So I don’t believe the problem is at the PHP site because I ran that in my browser and It gives the JSON response I need. The problem I’m facing is that the select is empty.

What configuration changes are required to upgrade Chakra UI v2 to v3?

I’m upgrading my project from Chakra UI v2 to v3, and I need help updating my custom theme.ts file to be fully compatible with Chakra UI v3.

Here’s my current theme.ts file written for Chakra UI v2:

import { extendTheme } from '@chakra-ui/react'

const theme = extendTheme({
  styles: {
    global: {
      body: {
        fontFamily: 'Inter, system-ui, sans-serif',
        fontSize: '16px',
        fontWeight: 400,
        lineHeight: 1.6,
      },
    },
  },
  fonts: {
    heading: 'Bebas Neue, sans-serif',
    body: 'Inter, system-ui, sans-serif',
  },
  components: {
    Heading: {
      baseStyle: {
        letterSpacing: '0.05em',
        textTransform: 'uppercase',
      },
      variants: {
        hero: {
          fontSize: ['4xl', '5xl', '6xl'],
          letterSpacing: '0.08em',
          textShadow: '2px 2px 4px rgba(0,0,0,0.3)',
        },
      },
    },
    Text: {
      baseStyle: {
        fontFamily: 'Inter, system-ui, sans-serif',
      },
    },
  },
  colors: {
    brand: {
      900: '#3C2A21',
      800: '#5C3D2E',
      700: '#B85C38',
    },
    background: {
      100: '#F2E3DB',
    },
    text: {
      900: '#1A1A1A',
      100: '#FFFFFF',
    },
  },
})

export default theme

My question is:

What changes are required to make this theme configuration fully compatible with Chakra UI v3?
Are there any breaking changes or improvements I should be aware of, especially regarding component theming or color tokens?

Upgradation of chakra UI v2 to v3

I’m upgrading my project from Chakra UI v2 to v3, and I need help updating my custom theme.ts file to be fully compatible with Chakra UI v3.

Here’s my current theme.ts file written for Chakra UI v2:

import { extendTheme } from '@chakra-ui/react'

const theme = extendTheme({
  styles: {
    global: {
      body: {
        fontFamily: 'Inter, system-ui, sans-serif',
        fontSize: '16px',
        fontWeight: 400,
        lineHeight: 1.6,
      },
    },
  },
  fonts: {
    heading: 'Bebas Neue, sans-serif',
    body: 'Inter, system-ui, sans-serif',
  },
  components: {
    Heading: {
      baseStyle: {
        letterSpacing: '0.05em',
        textTransform: 'uppercase',
      },
      variants: {
        hero: {
          fontSize: ['4xl', '5xl', '6xl'],
          letterSpacing: '0.08em',
          textShadow: '2px 2px 4px rgba(0,0,0,0.3)',
        },
      },
    },
    Text: {
      baseStyle: {
        fontFamily: 'Inter, system-ui, sans-serif',
      },
    },
  },
  colors: {
    brand: {
      900: '#3C2A21',
      800: '#5C3D2E',
      700: '#B85C38',
    },
    background: {
      100: '#F2E3DB',
    },
    text: {
      900: '#1A1A1A',
      100: '#FFFFFF',
    },
  },
})

export default theme

My question is:

What changes are required to make this theme configuration fully compatible with Chakra UI v3?
Are there any breaking changes or improvements I should be aware of, especially regarding component theming or color tokens?

Fully Expanded Multi-Select Checkboxes

My company is moving away from Filemaker and we are rewriting all those applications in .Net (Razor). The one feature we are having issues trying to recreate in .NET is the ability to display the select dropdown options as follows:

  • fully expanded (i.e., displaying all available options without using scrollbars – using mutli-columns if necessary),
  • options listed as checkboxes so more than one can be selected, and
  • the options box staying open until all items have been selected.

I’ve attached a sample image (made in Excel) to, hopefully, provide more clarification as to what we are trying to accomplish.
Fully Expanded Multi-Select Checkboxes

Any assistance with this is greatly appreciated. Thanks.

changing the resource structure @vite blade directive throws Exception

I added a new laravel 12 project and I have this structure in the resources folder:

resources

-admin #the frontend for the admin
--js
--sass
--package.json
--vite.config.js

-store #the frontend for the store

-views
--admin
---app.blade.php

--store
---home.blade.php

The admin will be an SPA and the store…I don’t know yet 🙂

The problem is with the admin when run the dev server using vite

Vite manifest not found at: /var/www/my-store/public/build/manifest.json

The app.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{{ config('app.name') }}</title>
    @vite(['resources/admin/sass/app.scss', 'resources/admin/js/app.js'])
</head>
<body>
<div id="app"></div>
</body>
</html>

The router web.php

Route::get('/', function () {
    return view('store.home');
});

Route::get('/administration{any}', function () {
    return view('admin.app');
})->where('any', '^(?!api).*$');

The vite.config.js (<– I think here is the problem… I am missing something…..)

import {defineConfig} from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue';

export default defineConfig({
    root: 'resources/admin',
    build: {
        outDir: '../../public/admin',
    },
    plugins: [
        laravel({
            input: ['sass/app.scss', 'js/app.js'],
            publicDirectory: '../../public/admin',
            refresh: true,
        }),
        vue({
            template: {
                transformAssetUrls: {
                    base: null,
                    includeAbsolute: false,
                },
            },
        }),
    ],   
    resolve: {
        alias: {
            '@': '/js',
        }
    },
    server: {
        host: '0.0.0.0',
        hmr: {
            clientPort: 5173,
            host: 'localhost',
        },
        fs: {
            cachedChecks: false
        }
    }
});

Package.json

{
    "private": true,
    "type": "module",
    "scripts": {
        "build": "vite build",
        "dev": "vite"
    },
    "devDependencies": {
        "@vitejs/plugin-vue": "^5.2.1",
        "laravel-vite-plugin": "^1.1.1",
        "lodash": "^4.17.21",
        "sass": "^1.83.1",
        "sass-loader": "^16.0.4",
        "vite": "^6.0.7"
    },
    "dependencies": {
        "@coreui/coreui": "^5.2.0",        
        "axios": "^1.7.9",
        "bootstrap-icons": "^1.11.3",     
        "pinia": "^2.3.0",      
        "vue": "^3.5.13",        
        "vue-i18n": "^11.0.1",      
        "vue-router": "^4.5.0"     
    }
}

When running npm run dev

  VITE v6.3.5  ready in 214 ms

  ➜  Local:   http://localhost:5173/
  ➜  Network: http://192.168.1.24:5173/
  ➜  press h + enter to show help

  LARAVEL   plugin v1.2.0

  ➜  APP_URL: undefined

but when accesing the administration page, it throws that exception IlluminateFoundationViteManifestNotFoundException

What else I need to do? Or what I did wrong in the vite.config.js ?

Sankey Chart with arrows with data box

Goal:
Im trying to add a create a sankey chart for a webpage that shows data that is filtered out as its processed through a system. I need the charts to show the arrows, with the weight of the arrows corresponding to the data weight at that level. And if possible id like to have the arrows point to a div box that I can populate with additional detail on why the data was filtered at that level (e.g. Filter 1 : Reason 1 : 100 counts). Im using HTML / JS

Drawing-of-Aim

So far I’ve tried using d3 and google libs which produce great looking sankey charts, but not with the arrows, or with the boxes I can populate. Or at least I havnt been able to find how to link those.

So far ive got so far in a stand alone example

<!DOCTYPE html>
<html>
  <head>
    <title>Sankey With Clean Layout</title>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <style>
      body {
        font-family: sans-serif;
        padding: 20px;
      }
      #sankey {
        width: 1400px;
        height: 600px;
        margin: auto;
      }
    </style>
    <script type="text/javascript">
      google.charts.load('current', { packages: ['sankey'] });
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {
        const data = new google.visualization.DataTable();
        data.addColumn('string', 'From');
        data.addColumn('string', 'To');
        data.addColumn('number', 'Weight');

        data.addRows([
          // Stage 1: Filter 1
          ['Request', 'Filter 1 Pass', 70],
          ['Request', 'Filter 1 Error', 30],

          // Stage 2: Filter 2
          ['Filter 1 Pass', 'Filter 2 Pass', 50],
          ['Filter 1 Pass', 'Filter 2 Error', 20],

          // Final success
          ['Filter 2 Pass', 'Success', 50],

          // Dummies to push spacing — hidden by giving them empty labels
          ['Filter 1 Error', '', 0.0001],
          ['Filter 2 Error', '', 0.0001],
        ]);

        const options = {
          sankey: {
            node: {
              nodePadding: 40,
              label: { fontSize: 14, color: '#000' }
            },
            link: {
              colorMode: 'gradient',
              colors: ['#0f9d58', '#ea4335', '#fbbc05']
            }
          }
        };

        const chart = new google.visualization.Sankey(document.getElementById('sankey'));
        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <h2>Sankey Diagram</h2>
    <div id="sankey"></div>
  </body>
</html>

which produces

HTML-sankey-example

I can see a library in python that produces svg i can use
matplotlib
But thats a static svg, hard to work into my html especially when I need to update the data, and would lose some of the interactivity

Am I on the right track with these libs ?
It seems weird to me that the libs mentioned dont add the support im looking for out of the box from what I see. Sankey charts with arrows and data boxes dont seem uncommon in practice. I could use a point in the right direction

JavaScript case-insensitive comparison for Unicode

If I understand correctly, various standards suggest that to compare strings case-insensitively, we should do full case folding and compare the results.

Python has .casefold(), so the method can be implemented easily.

Unfortunately, I couldn’t find a library for case folding in JavaScript. https://github.com/ar-nelson/foldcase is the most promising one, but it’s not maintained and out of date (which means it’s currently wrong).

It might appear that there is a more direct way to do case-insensitive comparison in JavaScript: Intl.Collator. Sadly, various modes of Intl.Collator seem to either go too far, or too little.

Here’s my test cases:

  • x = "á İ ß ꮳꮃꭹ"
  • y = "á i̇ ss ᏣᎳᎩ"
  • z = "a i̇ ß ᏣᎳᎩ"

In Python:

>>> x.casefold() == y.casefold()
True
>>> x.casefold() == z.casefold()
False

In JavaScript:

With the base mode:

> new Intl.Collator('en', { sensitivity: 'base' }).compare(x, y) === 0
true // good
> new Intl.Collator('en', { sensitivity: 'base' }).compare(x, z) === 0
true // bad

With the accent mode:

> new Intl.Collator('en', { sensitivity: 'accent' }).compare(x, y) === 0
false // bad
> new Intl.Collator('en', { sensitivity: 'accent' }).compare(x, z) === 0
false // good

So what do I do for JavaScript (besides implementing it myself / forking https://github.com/ar-nelson/foldcase and keeping it up-to-date)?