If I click a link directly from a textfield, does onblur consistently fire before the link?

I have a text input and a link used as a button set up on my website like so:

<input type="text" onblur="blurfunction()">
<a href="javascript:buttonfunction()">Button</a>

It’s important for my functionality to have blurfunction() always fire before buttonfunction(), even if the link is clicked directly without exiting the text field. From my limited testing in latest Chrome and Firefox clicking on the link directly from the text field consistently deselects the text field and fires blurfunction() before handling the link click and firing buttonfunction().

Can I expect this behaviour to be consistent across all browsers/devices? Is the order these calls happen defined in the HTML/JavaScript spec or could implementations differ between browsers?

Getting user data with Kinde auth in Remix

I am using Kinde for authentication in my remix app.

import { handleAuth, getKindeSession } from '@kinde-oss/kinde-remix-sdk'
import { LoaderFunctionArgs } from '@remix-run/node'

export async function loader({ params, request }: LoaderFunctionArgs) {
  return await handleAuth(request, params.index, {
    async onRedirectCallback() {
      const { getUserProfile } = await getKindeSession(request)
      const user = await getUserProfile()
      //TODO: Create user in Supabase
      console.log('This is called after the user is authenticated!', user)
    },
  })
}

This is the auth function. It works, I can login, log out and I have a protected page.
I am using Supabase as a database. So after authentication I want to create a profile in supabase for which I need the users details. The console.log keeps being undefined however. How can I access the user right after authentication?

how to hide the scrolled content behind the transparent sticky table head?

i am using React-Virtuoso library with material-ui table. i am stuck in a issue from yesterday,my table head is sticky and have transparent background same for table rows also. i dont want any another color.
when i scroll the table rows i can see them behind the table head. z-index cant fix the issue because of background color. please guys help me to fix this issue.
what i want is when i scroll the table rows shouldnt visible behind table head.
senior developers help needed.
codesandbox link : https://codesandbox.io/p/sandbox/epic-shtern-3jhn7q?workspaceId=b878446b-0701-41fb-b944-d231bbae84f1
here’s complete code:

import * as React from "react";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import { TableVirtuoso } from "react-virtuoso";

const sample = [
  ["Frozen yoghurt", 159, 6.0, 24, 4.0],
  ["Ice cream sandwich", 237, 9.0, 37, 4.3],
  ["Eclair", 262, 16.0, 24, 6.0],
  ["Cupcake", 305, 3.7, 67, 4.3],
  ["Gingerbread", 356, 16.0, 49, 3.9],
];

function createData(id, dessert, calories, fat, carbs, protein) {
  return { id, dessert, calories, fat, carbs, protein };
}

const columns = [
  {
    width: 200,
    label: "Dessert",
    dataKey: "dessert",
  },
  {
    width: 120,
    label: "Caloriesu00A0(g)",
    dataKey: "calories",
    numeric: true,
  },
  {
    width: 120,
    label: "Fatu00A0(g)",
    dataKey: "fat",
    numeric: true,
  },
  {
    width: 120,
    label: "Carbsu00A0(g)",
    dataKey: "carbs",
    numeric: true,
  },
  {
    width: 120,
    label: "Proteinu00A0(g)",
    dataKey: "protein",
    numeric: true,
  },
];

const rows = Array.from({ length: 200 }, (_, index) => {
  const randomSelection = sample[Math.floor(Math.random() * sample.length)];
  return createData(index, ...randomSelection);
});

const VirtuosoTableComponents = {
  Scroller: React.forwardRef((props, ref) => (
    <TableContainer {...props} ref={ref} />
  )),
  Table: (props) => (
    <Table
      {...props}
      sx={{
        borderCollapse: "separate",
        borderSpacing: "0px 8px",
      }}
    />
  ),
  TableHead: React.forwardRef((props, ref) => (
    <TableHead
      {...props}
      ref={ref}
      style={{
        background: "rgba(255, 255, 255, 0.1)",
        position: "sticky",
        zIndex: 2,
        top: "8px",
      }}
    />
  )),
  TableRow: React.forwardRef((props, ref) => (
    <TableRow
      {...props}
      ref={ref}
      sx={{
        background: "rgba(255, 255, 255, 0.1)",
      }}
    />
  )),
  TableBody: React.forwardRef((props, ref) => (
    <TableBody {...props} ref={ref} />
  )),
};

function fixedHeaderContent() {
  return (
    <TableRow>
      {columns.map((column) => (
        <TableCell
          key={column.dataKey}
          variant="head"
          align={column.numeric || false ? "right" : "left"}
          sx={{
            borderTop: "1px solid rgba( 255, 255, 255, 0.18 )",
            borderBottom: "1px solid rgba( 255, 255, 255, 0.18 )",
            "&:first-of-type": {
              borderLeft: "1px solid rgba( 255, 255, 255, 0.18 )",
              borderTopLeftRadius: "10px",
              borderBottomLeftRadius: "10px",
            },
            "&:last-of-type": {
              borderRight: "1px solid rgba( 255, 255, 255, 0.18 )",
              borderTopRightRadius: "10px",
              borderBottomRightRadius: "10px",
            },
          }}
        >
          {column.label}
        </TableCell>
      ))}
    </TableRow>
  );
}

function rowContent(_index, row) {
  return (
    <React.Fragment>
      {columns.map((column) => (
        <TableCell
          key={column.dataKey}
          align={column.numeric || false ? "right" : "left"}
          style={{
            borderTop: "1px solid rgba( 255, 255, 255, 0.18 )",
            borderBottom: "1px solid rgba( 255, 255, 255, 0.18 )",
            "&:first-of-type": {
              borderLeft: "1px solid rgba( 255, 255, 255, 0.18 )",
              borderTopLeftRadius: "10px",
              borderBottomLeftRadius: "10px",
            },
            "&:last-of-type": {
              borderRight: "1px solid rgba( 255, 255, 255, 0.18 )",
              borderTopRightRadius: "10px",
              borderBottomRightRadius: "10px",
            },
          }}
        >
          {row[column.dataKey]}
        </TableCell>
      ))}
    </React.Fragment>
  );
}

export default function ReactVirtualizedTable() {
  return (
    <div
      style={{
        height: 400,
        width: "100%",
        background: "rgba(255, 255, 255, 0.1)",
      }}
    >
      <TableVirtuoso
        data={rows}
        components={VirtuosoTableComponents}
        fixedHeaderContent={fixedHeaderContent}
        itemContent={rowContent}
      />
    </div>
  );
}

i dont want to see table row scrolled behind the table head.

How to call a js function that is fetched?

I have a react app where I try to fetch some functions from a js file:

useEffect(() => {
  const todayDate = new Date();

  fetch("https://raw.githubusercontent.com/courseraap/capstone/main/api.js")
    .then((response) => {
      if (!response.ok) {
        throw new Error("Network response was not ok");
      }
      return response.text();
    })
    .then((textResponse) => {
      console.log("textResponse :>> ", textResponse);

      const scriptFunction = new Function(textResponse);
      scriptFunction();

      window.fetchAPI(todayDate); // error, it is not a function. window.fetchAPI is undefined

    });

}, []);

I’ve read that if I call the response this way it will add those function objects to the window object, which is not happening for me for some reasons. What am I missing here?

The url is valid, so it can be checked the function is there.

Making calculations in a HTML table

I have a created a HTML table which is editable.
The table contains some cells are predefined with the numbers 1-5, than there is section where the user can enter data and in the last column there should be the result of the data of the previous cells. Now I want the add a formula like you have for instances with Excel. How I can make calculations in the HTML table with Javascript or any other method?

Details table

enter image description here

Column 1: packages is predefined
Column 2: here user can add weight in kg
Column 3: user adds here the length
Column 4: user adds here the width
Column 5: user adds here height
Column 6: user adds split (%)
Column 7: Volume weight = result formule is:length x width x height x 200

HTML table

.package_details {
  overflow: auto;
  width: 100%;
}

.package_details table {
  border: 1px solid #000000;
  height: 100%;
  width: 100%;
  table-layout: fixed;
  border-collapse: collapse;
  border-spacing: 1px;
  text-align: center;
}

.package_details caption {
  caption-side: top;
  text-align: left;
}

.package_details th {
  border: 1px solid #000000;
  background-color: #5A7C95;
  color: #ffffff;
  padding: 5px;
}

.package_details td {
  border: 1px solid #000000;
  background-color: #ffffff;
  color: #000000;
  padding: 5px;
}
</p>
<div class="package_details" tabindex="0" role="region">
  <table>
    <caption>
      <p><strong>Volume weight = L X W X H * 200</strong></p>
    </caption>
    <thead>
      <tr>
        <th>Packages</th>
        <th>Weight (kg)</th>
        <th>
          <p>Length (cm)</p>
        </th>
        <th>Width (cm)</th>
        <th>Height (cm)</th>
        <th>Split (%)</th>
        <th>*Volume weight</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td> </td>
      </tr>
      <tr>
        <td>2</td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td> </td>
      </tr>
      <tr>
        <td>3</td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td> </td>
      </tr>
      <tr>
        <td>4</td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td> </td>
      </tr>
      <tr>
        <td>5</td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td contenteditable="true"> </td>
        <td> </td>
      </tr>
    </tbody>
  </table>
  <div style="margin-top: 8px;"> </div>
</div>

What I tried
I did some research and many posts mention adding javascript to make calculations. I tried some but no success. Further I tried to add a formula in the last column to make calculations. Sadly not results.

What are some lesser-known JavaScript tips or keyboard shortcuts that have significantly improved your productivity as a developer? [closed]

I’m working on improving my JavaScript skills and trying to boost my productivity while coding. I know there are many helpful tips and keyboard shortcuts that can make coding faster and more efficient, but I feel like I’m missing out on some of the more advanced tricks. I’d love to hear about any tips, shortcuts, or practices that others have found really useful in their day-to-day development.

I’ve tried using some basic keyboard shortcuts like Ctrl + / to comment code and Alt + Shift + F for auto-formatting, but I feel like there’s more I could be leveraging.

‘Multipart: Boundary not found’ with React Fetch POST request, but works with Postman

I’m trying to send an image and two text fields to the express server, but it gives the error “Multipart: Boundary not found”.

    const handleFileUpload = async () => {
    if (!selectedFile) {
      Alert.alert('Ошибка', 'Выберите файл для загрузки');
      return;
    }
  
    const formData = new FormData();
    formData.append('image', {
      uri: selectedFile.uri,
      type: selectedFile.type,
      name: selectedFile.fileName || 'image.png',
    });
    formData.append('title', newImageTitleFile);
    formData.append('description', newImageDescriptionFile);
  
    try {
      const response = await fetch('http://localhost:5000/api/images/upload', {
        method: 'POST',
        body: formData,
      });
  
      if (!response.ok) {
        throw new Error('Ошибка загрузки файла');
      }
  
      const data = await response.json();
      console.log('Загружено:', data);
    } catch (error) {
      console.error('Ошибка:', error);
    }
  };

I tried to remove the header ‘Content-Type’: ‘multipart/form-data’, nothing changes.

TS error when building Svelte 5 component that renders either anchor or button element based on presence of href prop

I’m trying to create a Svelte 5 component that renders either a button or anchor element based on the presence of a href prop, however I’m running into a TS error.

Button.svelte

<script lang="ts">
  import type { HTMLButtonAttributes, HTMLAnchorAttributes } from 'svelte/elements';

  type Props = HTMLAnchorAttributes | HTMLButtonAttributes;
  
  const {
    href,
    children,
    ...restProps
  }: Props = $props();
</script>

{#if href}
  <a {href} {...restProps}>
    {@render children()}
  </a>
{:else}
  <button {...restProps}>
    {@render children()}
  </button>
{/if}

The above produces two errors:

  1. When destructuring props: href does not exist on Props type.
  2. When spreading restProps: Argument of type … is not assignable to parameter of type ‘HTMLProps<“a”, HTMLAtributes>’

I thought checking for the existence of href would act as a type guard allowing me to spread the correct props on the correct element.

Any insights appreciated. Thanks in advance.

Swapping two children of a parent node in JS

I have a parent div of nine divs, that each has a different background image. My task is to, whenever, I click on any of the divs except the targetDiv, the div gets swapped by the targetDiv in the DOM. So, here is the code:

function swap(e){
    let parent=document.getElementsByClassName('container')[0];
    swapDivsByBackground(parent,e.style.background);
}

function swapDivsByBackground(parent, bgImage1) {

    const children = Array.from(parent.children);
    const moveDiv = children.find(div => div.style.background.includes(bgImage1));
    if(!moveDiv) 
        return;

    const moveIndex = children.indexOf(moveDiv);
    const targetIndex = children.indexOf(targetDiv);

    parent.removeChild(moveDiv);
    parent.removeChild(targetDiv);
    
try{
    parent.insertBefore(moveDiv, children[moveIndex+1] || null);
}
catch(e){
    console.log(moveIndex+1);
    console.log(children[moveIndex+1]);
    console.log(e.message);
}
try{
    parent.insertBefore(targetDiv, children[targetIndex+1] || null);
}
catch(e){
    console.log(targetIndex+1);
    console.log(children[targetIndex+1]);
    console.log(e.message);
}
}

I am seriously facing some issues here. Sometimes, there are no swaps, and sometimes, I even get a error that says:

Failed to execute ‘insertBefore’ on ‘Node’: The node before which the new node is to be inserted is not a child of this node.

But alongside, I also receive the console messages from console.log(moveIndex+1); and console.log(children[moveIndex+1]);, that shows a valid div reference. But, if the node is not a child, then why are these messages shown? They should have shown undefined.

How to drag and drop a div inside another div

I have the following HTML code, which creates a div called “paddle” inside a div called “board”. I’m preparing a small game of Pong and the “paddle” div represents the paddle that will receive the ball.

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pong Game</title>
    <link rel="stylesheet" href="estilo.css">
    <script src="script.js"></script>
</head>
<body>
    <div id="board">
        <div id="paddle"></div>
    </div>
</body>
</html>
#board {
    margin: 0 auto;
    background-color: black;
    border-top: 5px solid skyblue;
    border-bottom: 5px solid skyblue;
    width: 500px;
    height: 500px;
    position: relative;
}

#paddle {
    background-color: skyblue;
    width: 10px;
    height: 50px;
    position: absolute;
    top: 250px;
    left: 480px;
    cursor: pointer;
}

I need you to help me with a JavaScript code that Drags and Drops the “paddle” div within the limits of the “board” div and only vertically

Sometimes CSS and JS not loading with error 500 [closed]

I am using ASP.Net Core 8 WebApp. when you open the website, sometimes css and js files not loading and when you see console, all of them has error 500. after you reload the page, all of them load correctly.

what is the problem???

by the way it’s a simple company website and it doesn’t have a lot of c# code for rendering. most of it is static html. it is hosted on shared hosting (Plesk) and sql server 2022. it is not sql problem because this problem existed before any database creation. I searched for this problem and found that maybe this is a server problem or server is on high load! but I don’t think so. because as I mentioned earlier, It doesn’t have heavy process. just a simple webpage. I can see this problem even on pages that has no code and just return View()

by the way I should mention that all the HTML codes loads and just css and js files not loading correctly and with a reload, all loads correctly

middlewares:

app.UseWebOptimizer();
app.UseHttpsRedirection();
app.UseStaticFiles(new StaticFileOptions()
{
    OnPrepareResponse = ctx =>
        {
        var path = ctx.File.PhysicalPath ?? "";

        if (path.EndsWith(".woff2") || path.EndsWith(".webp") || path.EndsWith(".png") || path.EndsWith(".jpeg") || path.EndsWith(".jpg"))
        {
        ctx.Context.Response.Headers.Append("Cache-Control", "max-age=31536000,immutable");
        }
    }
});
app.UseResponseCompression();

you can see it on this url: bineshdev.com

this is what it looks like:

enter image description here

Uncaught (in promise) TypeError: google.maps.importLibrary is not a function – Map not loading

Using google maps API, map seems to load 20% of the time. Currently getting the above error. The following is my php:

<script>
        async function initMap() {
            const { Map, InfoWindow } = await google.maps.importLibrary("maps");
            const { AdvancedMarkerElement, PinElement } = await google.maps.importLibrary(
                "marker",
            );
        }
        document.addEventListener('DOMContentLoaded', (event) => {
                initMap();
        });
</script>

<div class="search">
        <input id="autocomplete" placeholder="Enter address, city, or zip/postal code" type="text">
</div>
<div id="loadMap" style="height: 600px; width: 100%;"></div>

<script src="https://maps.google.com/maps/api/js?v=weekly&key=KEY&libraries=places&loading=async&solution_channel=GMP_guides_locatorplus_v2_a"></script>

Expecting the map to load 100% of the time.

CSS: How to toggle the borders of a specific table column without twitching

function toggleBorders() {
  table.tHead.firstElementChild.children[1].classList.toggle('thick-border');
  Array.from(table.tBodies[0].children).forEach(row => row.children[1].classList.toggle('thick-border'));
}
table {
  border-collapse: collapse;
}

th.thick-border,
td.thick-border {
  border: 3px solid coral;
  border-top: none;
  border-bottom: none;
}
<table id="table">
  <thead>
    <tr>
      <th>h1</th> <th>h2</th> <th>h3</th> <th>h4</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>11</td> <td>12</td> <td>13</td> <td>14</td>
    </tr>
    <tr>
      <td>21</td> <td>22</td> <td>23</td> <td>24</td>
    </tr>
  </tbody>
</table>
<br>
<button id="btn" onclick="toggleBorders()">Click Me!</button>

Is there any way to toggle the column’s borders without twitching?
And without thickening initial border width of other columns?

Maybe with shadows or gradients or somehow else

once audio start playing in brower on pausing it is not getting paused

function stopRingtone() {
    if (!isRingtonePlaying) return;
    if (ringtoneTimeout) {
        clearTimeout(ringtoneTimeout);
        ringtoneTimeout = null;
    }
    if (sourceNode) {
        sourceNode.stop();
        sourceNode.disconnect();
        sourceNode = null;
    }

    if (gainNode) {
        gainNode.disconnect();
        gainNode = null;
    }

    if (audioContext) {
        audioContext.close().then(() => {
            audioContext = null;
            audioBuffer = null;
            console.log("AudioContext closed and reset.");
        }).catch((err) => {
            console.error("Error closing AudioContext:", err);
        });
    }
}

function playAudioLoop() {
 
    sourceNode = audioContext.createBufferSource();
    sourceNode.buffer = audioBuffer;
    sourceNode.connect(gainNode);
    sourceNode.start(0);

    const loopDuration = audioBuffer.duration * 1000; // Convert to milliseconds
    const targetDuration = 12000; // 12 seconds in milliseconds

    ringtoneTimeout = setTimeout(() => {
        if (isRingtonePlaying) {
            const elapsedTime = audioContext.currentTime * 1000; 
            if (elapsedTime < targetDuration) {
                playAudioLoop(); // Continue looping
            } else {
                stopRingtone(); // Stop after target duration
            }
        }
    }, Math.min(loopDuration, targetDuration));
}

Pause the audio when stopRingtone() function is called.on implementing Custom ringtone for call, on accepting or other call events audio should be stopped , here it is not stopping , it continuously keeps on playing