Triggering an uncaught error synchronously while executing a chain of callbacks, without preventing execution of subsequent callbacks

Context:

When executing callbacks that were added with addEventListener, the browser seemingly has a way of executing the callbacks in order, and synchronously triggering an uncaught error if one fails, without disrupting/preventing the subsequent handlers from being executed.

For example:

let button = document.createElement("button");
button.textContent = 'Click';
document.body.append(button);

button.addEventListener('click', () => {
  console.log('1st listener');
  throw new Error('error');
});

button.addEventListener('click', () => {
  console.log('2nd listener');
});

console.log("Before click");
button.click();
console.log("After click");

shows these logs:

Before click
1st listener
Uncaught Error: error
2nd listener
After click

The key point here is that the error occurs between the two listeners.

Question:

I’m wondering how to emulate this behavior with my own addEventListener-like framework. Here’s some example code to demonstrate what I’m trying to achieve:

let callbacks = [
  () => { console.log('1st listener'); throw new Error("error"); },
  () => { console.log('2nd listener') },
];

function triggerHandlers() {
  for(let cb of callbacks) {
    try {
      cb();
    } catch(e) { 
      console.error(e); // how to *synchronously* trigger an uncaught error here without interrupting the for loop?
    }
  }
}

console.log("Before click");
triggerHandlers();
console.log("After click");

Possible Solutions:

  • Maybe using a finally block which recursively calls the function, instead of a for loop? This seems a bit hacky though. I’m hoping there’s a more straightforward approach that doesn’t require recursion.
  • Using the built-in EventTarget to side-step the problem. This isn’t really a viable solution in my case, except perhaps as a “hacky” solution that uses it “surgically” within the codebase to emulate the above behavior (i.e. not using it in the way it’s supposed to be used).

Non-Solutions:

  • Rethrowing the error via something like setTimeout(()=>throw e, 0) (or equivalent) does not work, since it’s not synchronous.

get scroll position of IG body region

I have page with different IG regions
first IG is saving Automatic every time interval using :
apex.region("PENDINGORDERS").widget().interactiveGrid("getActions").invoke("save");

this reset the paganing of the region, I need to go to same position where the scrollbar was, so I’ve tried
savepos = $(window).scrollTop();
but this gets thw window scrollbar
so tried this
savepos = $("#PENDINGORDERS").scrollTop();

but it always gets 0

what i’m missing here

SPFx Application Customizer Footer: Show Only When Scrolled to Bottom

I’m developing a SharePoint Framework (SPFx) extension that adds a custom footer to SharePoint pages. While I’ve successfully implemented the footer using the bottom placeholder, it’s currently visible at all times. I want to modify the behavior so the footer only appears when the user scrolls to the bottom of the page.

    import { BaseApplicationCustomizer, PlaceholderContent, PlaceholderName } from '@microsoft/sp-application-base';
import { Footer } from './Component/Footer';
import { SPFI } from "@pnp/sp";
import * as React from 'react';
import * as ReactDom from 'react-dom';

export default class HelloWorldApplicationCustomizer extends BaseApplicationCustomizer<IHelloWorldApplicationCustomizerProperties> {
  private _sp: SPFI;
  private _bottomPlaceholder: PlaceholderContent | undefined;

  public onInit(): Promise<void> {
    this.context.placeholderProvider.changedEvent.add(this, this.renderPlaceHolders);
    return Promise.resolve();
  }

  private renderPlaceHolders(): void {
    const linksListName: string = this.properties.linksListName || 'FooterLinks';
    const feedbackListName: string = this.properties.feedbackListName || 'Feedback';

    this._sp = getSP(this.context);
    if (!this._bottomPlaceholder) {
      this._bottomPlaceholder = this.context.placeholderProvider.tryCreateContent(
        PlaceholderName.Bottom
      );

      if (this._bottomPlaceholder && this._bottomPlaceholder.domElement) {
        const element: React.ReactElement<{}> = React.createElement(
          Footer,
          {
            sp: this._sp,
            linksListName: linksListName,
            feedbackListName: feedbackListName
          }
        );
        ReactDom.render(element, this._bottomPlaceholder.domElement);
      }
    }
  }
}

Expected Behavior

Footer should be hidden by default
Footer should appear only when user scrolls to/near the bottom of the page
Footer should hide again when scrolling back up
Transitions should be smooth

What I’ve Tried
I’ve attempted to use the bottom placeholder provided by SPFx, but I’m unable to control its visibility based on scroll position. I’m not sure about:

The best way to handle scroll events in an SPFx extension
How to properly manage the footer’s visibility
How to implement smooth transitions

Question
How can I modify my SPFx extension to make the footer appear only when scrolling to the bottom of the page? I need a solution that:

Works with React components
Handles scroll events properly
Manages component lifecycle correctly
Implements smooth transitions

Environment

SharePoint Framework version: [your version]
React version: [your version]
Browser: Chrome/Edge/Firefox

Any help would be greatly appreciated!

I’m having issues displaying changes to values when a user clicks a button

I’ve been working on a WordPress project previously developed by someone else. As the project is WordPress-based, most of the heavy lifting is done by PHP. However, some of the work is being done using jQuery, and as I only have experience with vanilla JavaScript, I’ve had to learn by doing. So far, this has been okay, but I’ve hit the limit of my small amount of knowledge and exhausted all the online resources I can find. Before I discuss my issue in detail, I’ll give you an overview of the project and what the code does.

The project is a website personal trainers can use to create exercise programs they can send to clients. Clients can then log in and view the created exercise program at home. When a PT creates a program, a catalogue of widgets for each exercise is displayed on the right side of the page. The PT adds an exercise to the program from the catalogue by clicking on its add button. It then goes into a column on the left where the PT can change parts of the exercise, such as how long it takes to do an exercise or leave the settings already there by default.

Each exercise added to the lefthand column is part of a sortable list, and a hidden input identifies it with an ID number showing its position in the list.

<input class="id" type="hidden" name="exercises[1][id]" value="2370">

The data in the exercise is passed to the items in the list via data–* when the add button is clicked. In this case, the duration is in seconds.

data-exerduration="240". 

The information from the data–* items are then picked up by the code and displayed.

I have hit a snag when implementing a new feature. When you add a value to the seconds field under dosage and press the chevron to hide the form, the displayed value for “secs” should change to match the value in the field. When you click the chevron to show the form again, the value for “secs” should change back to the value you had when the exercise was added. This is the expected functionality, but it starts to break down as more exercises are added.

After a second or third exercise is added, sometimes “secs” does not update to match the value in the seconds field and only changes after the chevron has been clicked several times. Other times, the value in the seconds field is displayed when the form is shown, and the default value for “secs” is displayed when the form is hidden. This is the reverse of what should be happening.

Please also note that if the seconds field is empty the value of “secs” should not change.

A working version of the code can be viewed on Codepen. https://codepen.io/GunShip03v2/pen/NPKKPZx

I’m not sure what else to try as I have reached the limit of my jQuery Knowledge. Simply put, I’m stuck and need someone with more experience to help me get this working. Your help would be greatly appreciated.

What is the use of bind method in ReactJS class component?

I am new to reactjs and currently I am doing a course in react. The below given code is confusing me. Because I am not understanding the use of Bind method in this code. the code is working fine without using bind. Am I missing something?

import React,{Component} from "react";

class BindNew extends Component{
    constructor(){
        super();
        this.state={
            name:"this is the old name"
        }
        this.ChangeName = this.ChangeName.bind(this)
    }
    ChangeName=()=>{
        this.setState({name:"this is the new name"})
    }
render(){
    return(
        <div>
            <button onClick={this.ChangeName}>click Here</button>
            <label>{this.state.name}</label>
        </div>
    )
}
}
export default BindNew;

How can I make a soft brush blend well with already painted areas?

In canvas js, the brush does not blend well if you paint it on a hidden canvas first, over already painted areas.
You can draw without a hidden layer, directly on the main canvas, but then you will not be able to make transparency using ctx.globalAlpha.

The brush borders are clearly visible above the already drawn image. You can reduce the number of steps, then the halo effect will not be noticeable, but I need many steps.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Canvas Brush Example</title>
    <style>
        canvas {
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <canvas id="canvas" width="400" height="200"></canvas>

    <script>

        function createBrush(size, color = 'rgba(0, 0, 0, 1)', hardness = 0.1) {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');

            const blur = size / 2 * (1 - hardness);
            const canvasSize = size + blur * 2;

            canvas.width = canvasSize;
            canvas.height = canvasSize;

            ctx.beginPath();
            ctx.arc(canvasSize / 2, canvasSize / 2, size / 2, 0, Math.PI * 2);
            ctx.shadowColor = color;
            ctx.shadowBlur = blur;
            ctx.fillStyle = color;
            ctx.fill();

            return canvas;
        }

        function drawLine(ctx, brush, startX, startY, endX, endY, brushSize, step = 10, alpha = 1) {
            const distance = Math.hypot(endX - startX, endY - startY);
            const steps = Math.ceil(distance / step);
            const deltaX = (endX - startX) / steps;
            const deltaY = (endY - startY) / steps;

        const tempCanvas = document.createElement('canvas');
            const tempCtx = tempCanvas.getContext('2d');

            for (let i = 0; i <= steps; i++) {
                const x = startX + deltaX * i;
                const y = startY + deltaY * i;
                tempCtx.drawImage(brush, x - brushSize / 2, y - brushSize / 2, brushSize, brushSize);
            }

        ctx.globalAlpha = alpha
            ctx.drawImage(tempCanvas, 0, 0, ctx.canvas.width, ctx.canvas.height);
        ctx.globalAlpha = 1
        }


        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');

        const brushSize = 40;
        const color = 'rgba(0, 136, 255, 1)';
        const hardness = 0.01;
        const brush = createBrush(brushSize, color, hardness);

    //frist line, step 0.01, brush hardness 0.01
        drawLine(ctx, brush, 50, 100, 250, 100, brushSize, 0.1);

    //second line, step 0.01, brush hardness 0.01   
        drawLine(ctx, brush, 50, 100 + brushSize / 2, 250, 100 + brushSize / 2, brushSize, 0.01);


    </script>
</body>
</html>

here screenshot two lines, and visible border in middle.

how do I connect an existing db to and existing webpage using js

I am making a website for a project and currently unable and do not know how to connect my existing database with my html and js code. I have tried to use various means of connections.

whenever I try to connect a function that involves the database to a button in html nothing happens. this only applies to the html as when I run the js it can query and add to the database. I would like to not have to learn an extra language on top of js to fix this issue but if it is required idm.

this is my code
html

i would like to implement the insertion into the database into the submit button to then add the data from the two input boxes into the database

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="login.css">
    <title>sign up</title>
</head>
<body>
    <a href="pg1.html"><button class="pagebt"><</button></a>
    <a href="login.html"><button class="pagebt">log in</button></a>
    <form >
        <div class="block">
            <h1>
                signUp
            </h1>
            <h2 id="username">username :</h2>
            <input type="text" class="input" id="username" >
            <h2>password :</h2>
            <input type="password" class="input" id="password">
            <div>
                <button class="intbut">submit</button>

            </div>
        </div>
    </form>
    <script src="signUp.js"></script>
</body>

</html>

js

const sqlite3 = require('sqlite3').verbose();


// Connect to the database
const db = new sqlite3.Database('./userData.db', sqlite3.OPEN_READWRITE, (err) => {
  if (err) {
    console.error("Error opening database:", err);
  } else {
    console.log("Connected to the database.");
  }
});

// Create table if not exists (ensure the table exists before inserting data)
let sql = `CREATE TABLE IF NOT EXISTS userData (
  id INTEGER PRIMARY KEY,
  userN TEXT,
  passW TEXT
)`;

db.run(sql, (err) => {
  if (err) {
    console.error("Error creating table:", err);
  } else {
    console.log("Table created or already exists.");
  }
});

// Insert data into the table

sql = 'INSERT INTO users(userN, passW) VALUES (?, ?)';
db.run(sql, ['userN', 'passW'], function(err) {
if (err) {
    console.error("Error inserting data:", err);
} else {
    console.log(`Row inserted with ID: ${this.lastID}`);
}
});


// Query the database to retrieve all users
sql = 'SELECT * FROM userData';
db.all(sql, [], (err, rows) => {
  if (err) {
    console.error("Error querying database:", err);
  } else {
    console.log("Users:", rows);
  }
});

// Close the database connection
db.close((err) => {
  if (err) {
    console.error("Error closing the database:", err);
  } else {
    console.log("Database connection closed.");
  }
});

Token Not Set in Browser Cookies in Production

I am working on a React application where I handle authentication by setting a token in cookies after the user logs in. I have set the token in cookies its getting set in local development. when its come to the production the token will not get set in the browser cookies. We have the two docker Images, one is for front end and one is for the backend. But the main Problem is my token is not getting set in Cookies.

My Environment:
Backend: Spring Boot and MySQL.
Frontend: React Js.
Api Handling:-=RTK Query.
Cloud Provider: Google Cloud Provider.
Cookie library: js-cookie

Verified the backend response contains the token.
Ensured the secure and sameSite attributes are set correctly(I have Removed Everything While Set the token).
Checked that my domain and subdomain match correctly.
checked that everything working fine in local.

import { createSlice } from "@reduxjs/toolkit";
import { authApis } from "./authApis";
import Cookies from "js-cookie";
const initialState = {
  token: Cookies.get("accessToken") || null,
  isLoggedIn: !!Cookies.get("accessToken"),
  successMessage: "Logeed in",
  errorMessage: "",
};
const setToken = (token) => {
  Cookies.set("accessToken", token, {
    // sameSite: "Strct",
    // secure: true,
  });
  console.log("accessToken", token);
};
const deleteCookie = (name) => {
  Cookies.remove(name, { path: "/" /*sameSite: "Strict"*/ });
};
const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder.addMatcher(
      authApis.endpoints.login.matchFulfilled,
      (state, action) => {
        const { token } = action.payload;
        state.token = token;
        state.isLoggedIn = true;
        console.log("token", token);
        setToken(token);
        //below everything is consoling
        console.log("Token retrieved:", state.token);
        console.log("Token Get set", Cookies.get("accessToken"));
      }
    );
    builder.addMatcher(
      authApis.endpoints.logout.matchFulfilled,
      (state, action) => {
        state.token = null;
        state.isLoggedIn = false;
        deleteCookie("accessToken");
        deleteCookie("roles");
        deleteCookie("isAdminView");
        console.log("Logout successful:", action.payload);
      }
    );
  },
});
export default authSlice.reducer;

What is the difference in the output of new URL(import.meta.url).href when using Webpack compared to Vite?

I have a question regarding the behavior of new URL(import.meta.url).href in different build tools.

In my Webpack project, it returns a file path like file:///...
In my Vite project, it returns a URL like http://localhost:5173/...
Can anyone explain to me why there is this difference? How can I do that if I want my Webpack project also to return a URL like http://localhost:8080?
I’m not sure what keywords to search for.

Nuxt 3 ssr custom error page (404) not showing in production mode

I have a code below

error.vue

<template>
  <NuxtLayout>
    <div class="prose">
        <template v-if="error.statusCode === 404">
          <h1>404!</h1>
          <p>Sorry, that page doesn't exist.</p>
        </template>
            <template v-else-if="error.statusCode === 500">
              <h1>500!</h1>
                <p>
                  <strong>{{ error.message }}</strong>
                </p>
      </template>
    </div>
  </NuxtLayout>
</template>


<script setup>
const error = useError();
</script>

This works fine when in dev mode (when entering wrong path it displays 404 error), but when project is built and uploaded to cloudflare pages, when entering wrong path it displays 500 error instead

Perfect Scrollbar Add new JS script problem

I am using a template with the Perfect-Scrollbar js library.

When I click on the add_content link from the menu on the index.php page and provide redirection, the add_content page opens, but although the header.php pages/add_content.php footer.php, which is available in add_content.php, appears, the I added to the bottom of the page does not appear when redirected. However, if I refresh the page, this new_script.js loads. Does anyone have any information about the solution to the problem?

Adding C# into a pre-existing React JS web application

I have built a web application using vanilla js and react js. Im looking to add a functionality (MSAL and Token Requests) that i would prefer to do in c#, is it possible to add c# classes and functionality into an existing react JS web app (that was started with the create-react-app command). Or would i need to start a new React with ASP.net project in VS?

Shrink address bar on Safari for mobile – JavaScript

Seen a lot of old threads (thread 1 and thread 2) but hasn’t been discussed lately, since the latest iOs deprecated the use of scrollTo and minimal-ui, requiring manual (human) scroll in order to shrink the address bar, is there any way around it so we can shrink the address bar on page loading, not requiring the user to manually scroll to shrink? Tried scrollTo, minimal-ui, "display": "standalone", "orientation": "portrait", in manifest.json however still hadn’t had luck. Any feedback is appreciated? page example I’ve been working with scrollTo

Apache Superset – Conditional Formatting on a column based on the values of another column?

I am using a Pivot Table v2 in Apache Superset. I have two metric columns: ‘Cost’ and ‘Percentage Diff.’ (I’ll refer to this as ‘%’).

My goal is: for every row, the background color of the ‘Cost’ cell depends on the value of the ‘%’ cell.

Example:

  • Customer A has ‘100$’ in Cost, and ‘+30%’ in ‘%’. The ‘100$’ should have a green background due to the +30%.
  • Customer B has ‘300$’ in Cost, and ‘-15%’ in ‘%’. The ‘300$’ should have a (fainter) red background due to the -15%.

With the current implementation of Pivot Table, as far as I can tell, conditional formatting is only available based on the value of the cell being formatted itself. Is there any plugin or does anyone have any general pointers into how I could solve this problem? I am more than happy to look into the code and modify it, although I’m experiencing difficulties due to lack of documentation of the codebase…

Thanks in advance and all the best!

transform/pivot array of objects based on values of a key and reconvert it back to original in javascript

I want be able to convert below array or objects with uniform keys, but have it pivoted or transformed into array of objects, but with as many objects as there are properties in an object, with each object now having the name of property along with keys for each value for a specified key in the original (in this case all the possible vales of they “year” from original array). And I also want to get this array re-transposed into original form.

I want to know if this is possible to do in a generic way so It can be done with any time of object and based on any of its key’s values.

Input:

[
    {
        "property0": "property0_2024",
        "property1": "property1_2024",
        "property2": "property2_2024",
        "property3": "property3_2024",
        "property4": "property4_2024",
        "year": "2024"
    },
    {
        "property0": "property0_2025",
        "property1": "property1_2025",
        "property2": "property2_2025",
        "property3": "property3_2025",
        "property4": "property4_2025",
        "year": "2025"
    },
    {
        "property0": "property0_2026",
        "property1": "property1_2026",
        "property2": "property2_2026",
        "property3": "property3_2026",
        "property4": "property4_2026",
        "year": "2026"
    },
    {
        "property0": "property0_2027",
        "property1": "property1_2027",
        "property2": "property2_2027",
        "property3": "property3_2027",
        "property4": "property4_2027",
        "year": "2027"
    }
]

Output:

[
    {
        "propertyName": "property0",
        "year_2024": "property0_2024",
        "year_2025": "property0_2025",
        "year_2026": "property0_2026",
        "year_2027": "property0_2027"
    },
    {
        "propertyName": "property1",
        "year_2024": "property1_2024",
        "year_2025": "property1_2025",
        "year_2026": "property1_2026",
        "year_2027": "property1_2027"
    },
    {
        "propertyName": "property2",
        "year_2024": "property2_2024",
        "year_2025": "property2_2025",
        "year_2026": "property2_2026",
        "year_2027": "property2_2027"
    },
    {
        "propertyName": "property3",
        "year_2024": "property3_2024",
        "year_2025": "property3_2025",
        "year_2026": "property3_2026",
        "year_2027": "property3_2027"
    },
    {
        "propertyName": "property4",
        "year_2024": "property4_2024",
        "year_2025": "property4_2025",
        "year_2026": "property4_2026",
        "year_2027": "property4_2027"
    }
]