How do I fix delayed audio when click in NextJs?

I’m working on a Next.js project and encountering an issue with audio playback in my application. I use the following code to play audio when a button is clicked:

export default function Home() {

  function playAudio() {
    const audio = new Audio("/audio/ball_kick.mp3");
    audio.play();
  }

  return (
    <>
      <button onClick={() => playAudio()} />
    </>
  );
}

The problem is that when the button is clicked, there is a slight delay and the audio is not synced with the button action. How can I resolve this issue to ensure that the audio plays without delay and is synchronized with the button click? Are there any approaches or techniques that can be used to make the audio playback more responsive?

Why CustomEvent remains unhandled in JS code

I’m trying to fire up a custom event and catch it by a child element, which doesn’t seem to work. What am I missing (I am aware of DOM-less solutions, but need to get it working with DOM)?

I tried a few different options including swapping child and parent to eliminate potential bubbling/tunneling issues, and tried the legacy Event class, but none seemed to work.

document.getElementById("parent").addEventListener("click", function() {
  window.dispatchEvent(new CustomEvent("test", {
    detail: "Hello"
  }));
});



document.getElementById("child").addEventListener("test", function(event) {
  console.info("Hello");
});
<button id="parent">Fire</button>
<div id="child" />

Google App script Wepp App for logged users only

I have been searching stack overflow for a solution but none worked yet and I am not really sure if I can do what I want to, but here is the scenario:

I have a Google app script that will return only this:

function doPost(e) {
  return ContentService.createTextOutput(JSON.stringify({status: "success", "data": "my-data"})).setMimeType(ContentService.MimeType.JSON);
}
function doGet(e) {
  return ContentService.createTextOutput(JSON.stringify({status: "success", "data": "my-data"})).setMimeType(ContentService.MimeType.JSON);
}

I have an app deployed with the current configurations:
Execute as: Me, Who has access: Anyone with Google Account

I am buinding a Javascript script that will run on the browser scope and call that app, however I want to have an oAuth and get an access token before calling it. However either I cannot find a solution or it doesn’t exist with only front-end solutions.

I tried using Javascript fetch, however I either get unauthorized responses or ‘opaque’ responses, I already figured out that one of the configurations of the fetch should be {redirect: ‘follow’}, because app script always redirects to a new URL.

I might not be able to use Google Cloud Platform internally for this purpose, that is why I didn’t go through the API deployment path.

I do not have a backend, this script will run either injected through a bookmark or if we get approval through a chrome extension, so it is browser scopped;

React-router-dom with a component outside of the router

I am trying to use react-router-dom to handle my React app navigation. I am running into some issues using the standard useNavigate function because my Header component is outside the Router.

I am trying to restructure the app to move my header inside the Router but when I do this the header does not appear.

Currently my header is rendered in my index.js file:

    <AppProvider>
      <Header />
      <AppRoutes />
    </AppProvider>

The AppRoutes uses createBrowserRouter:

import React from "react";
import { createBrowserRouter, RouterProvider } from "react-router-dom";

import App from "./App";
import { Header } from "./Header";
import { AppLayout } from "./AppLayout";
import { AccountHome } from "./pages/AccountHome/AccountHome";

const router = createBrowserRouter([
  {
    path: "/",
    element: <AppLayout />,
  },
  { path: "/account", element: <AccountHome /> },
]);

export const AppRoutes = ({ auth }) => {
  return <RouterProvider router={router} />;
};

And AppLayout uses Outlet:

export const AppLayout = () => {
  const {
    isAuthenticated,
    isPricingModalOpen,
    pricingOptions,
    setIsPricingModalOpen,
  } = useContext(AppContext);
  return (
    <>
      <PricingModal
        isPricingModalOpen={isPricingModalOpen}
        pricingOptions={pricingOptions}
        setIsPricingModalOpen={setIsPricingModalOpen}
      />
      {isAuthenticated ? <HomePage /> : <LandingPage />}
      <Outlet />
    </>
  );
};

I tried moving the Header into my AppLayout but then the header doesn’t appear on AccountHome

HTML Canvas “onmousedown” event and “mousedown” listener not firing

I have an HTML page with a canvas in the body defined as so:

<!DOCTYPE html>
<html>
<head>
    <script defer src="./js/canvas.js"></script>
    <link rel="stylesheet" href="./css/canvas.css">
</head>
<body>
    <canvas id="pinboard"></canvas>
</body>
</html>

In canvas.js I’ve written:

var canvas = document.getElementById("pinboard");

canvas.addEventListener("mousedown", function (e) {
    console.log("DOWN 1 " + e);
});

canvas.onmousedown = function (e) {
    console.log("DOWN 2 " + e);
}

This isn’t in a DOMContentLoaded listener, but I’ve tried with and without and it doesn’t work.

When I click on the canvas, I expect either “DOWN 1” to print, “DOWN 2” to print, or both, but neither of them are logging.

I’ve searched through quite a few posts but I can’t find anything that’s fixed my problem.

Runtime error: TypeError: Cannot read properties of undefined (reading ‘backdrop’)

I have a vue frontend, where I have to add snippet for one of the additional api call from backend. The vue file was working fine until I added the snippet to accomodate the api request coming from backend. The npm run serve doesnt throw any errors , but when I click on the module on the local frontend associated with vue file I am working on, it gives the run time error. The error is following.

Uncaught runtime errors:
×
ERROR
Cannot read properties of undefined (reading 'backdrop')
TypeError: Cannot read properties of undefined (reading 'backdrop')
    at Modal._initializeBackDrop (webpack-internal:///./node_modules/bootstrap/dist/js/bootstrap.esm.js:2510:39)
    at new Modal (webpack-internal:///./node_modules/bootstrap/dist/js/bootstrap.esm.js:2442:27)
    at Modal.getOrCreateInstance (webpack-internal:///./node_modules/bootstrap/dist/js/bootstrap.esm.js:704:41)
    at HTMLButtonElement.eval (webpack-internal:///./node_modules/bootstrap/dist/js/bootstrap.esm.js:2682:22)
    at HTMLDocument.handler (webpack-internal:///./node_modules/bootstrap/dist/js/bootstrap.esm.js:382:19)

Many articles suggested it might be the issue the DOM not fully loaded and some suggested its the bootstrap issue.

My initial code prior having issues (changes in the template section not shown as it didnt affect the code):

<script>
import StudyReportForm from "../forms/StudyReportForm";
import StudyReportEditForm from "../forms/StudyReportEditForm";

export default {
  name: "ManageStudyReportsModal",
  components: { StudyReportEditForm, StudyReportForm },
  data() {
    return {
      addCollapse: null,
      editCollapse: null,
      isUpdating: false,
      studyreports: [],
      selectedReports: [],
      meta: {
        totalItems: 0,
        totalPages: 0,
        currentPage: 1,
        pageSize: 10,
      },
      report: null,
    };
  },
  mounted() {
    this.getData();
  },
  methods: {
    toggleCollapseAddForm() {
      this.isUpdating = false;
      if (this.editCollapse) {
        this.editCollapse.hide();
      }
      if (!this.addCollapse) {
        this.addCollapse = new this.$bootstrap.Collapse(
          document.getElementById("addNewStudyReports")
        );
      }
      this.addCollapse.toggle();
    },
    collapseAddForm(type) {
      this.isUpdating = false;
      if (!this.addCollapse) {
        this.addCollapse = new this.$bootstrap.Collapse(
          document.getElementById("addNewStudyReports")
        );
      }
      if (type === "show") {
        this.addCollapse.show();
        if (this.editCollapse) {
          this.editCollapse.hide();
        }
      } else {
        this.addCollapse.hide();
      }
    },
    collapseEditForm(type) {
      if (!this.editCollapse) {
        this.editCollapse = new this.$bootstrap.Collapse(
          document.getElementById("editStudyReports")
        );
      }
      if (type === "show") {
        this.editCollapse.show();
        if (this.addCollapse) {
          this.addCollapse.hide();
        }
      } else {
        this.editCollapse.hide();
      }
    },
    collapseEditStudyReportsForm() {
      this.collapseEditForm("hide");
      this.report = {};
      this.isUpdating = false;
    },
    reportUpdated() {
      this.collapseEditStudyReportsForm();
      this.getData();
      this.$emit("reportUpdated");
    },
    cancelUpdate() {
      this.collapseEditStudyReportsForm();
    },
    reportAdded() {
      this.addCollapse.hide();
      this.getData();
      this.$emit("reportUpdated");
    },
    async deleteStudyReports(id) {
      await this.$confirm({
        message: `Are you sure?`,
        button: {
          no: "No",
          yes: "Yes",
        },
        callback: (confirm) => {
          if (confirm) {
            this.$repository.studyReports
              .delete(id)
              .then(() => {
                this.getData();
                this.$emit("reportUpdated");
                this.$toast.success("Report deleted");
              })
              .catch(() => {
                this.$toast.error("Deletion Failed");
              });
          }
        },
      });
    },
    editStudyReports(report) {
      if (this.addCollapse) {
        this.collapseAddForm("hide");
      }
      this.isUpdating = true;
      this.report = report;
      this.collapseEditForm("show");
    },
    async getData(page = 1) {
      this.meta.currentPage = page;

      let params = `?page_size=${this.meta.pageSize}&ordering=-uploaded_at`;

      if (this.meta.currentPage > 1) {
        params += `&page=${this.meta.currentPage}`;
      }

      await this.$repository.studyReports.filter(params).then((res) => {
        this.studyreports = res.data.results;
        this.meta.totalItems = res.data.count;
        this.meta.totalPages = Math.ceil(res.data.count / 10);
      });
    },
  },
};
</script>

I added the following change to the script file to (showing the added part only)…Its to accomodate the patch request sent to the backend just to update in_draft: false. Here I modified the mounted method and also added initializeModals() function.

Updated code: (added part only)

import { Collapse } from 'bootstrap';
export default {
........//code //.................
mounted() {
    this.$nextTick(() => {
      this.getData();
      this.initializeModals();
    });
  },
  methods: {
    initializeModals() {
      const addNewStudyReportsElem = document.getElementById("addNewStudyReports");
      if (addNewStudyReportsElem) {
        this.addCollapse = new Collapse(addNewStudyReportsElem, { toggle: false });
      }

      const editStudyReportsElem = document.getElementById("editStudyReports");
      if (editStudyReportsElem) {
        this.editCollapse = new Collapse(editStudyReportsElem, { toggle: false });
      }
    },

//………..added snippet for api below//………….

async handleCheckboxChange(reportId, isChecked) {
      this.isUpdating = true;
      try {
        if (isChecked) {
          // Check if the report is already in the selectedReports list
          if (!this.selectedReports.includes(reportId)) {
            this.selectedReports.push(reportId);
          }

          // Publish the report if checked
          await this.$repository.studyReports.edit({ in_draft: false }, reportId);
          this.$toast.success('Report published successfully.');
        } else {
          // Remove the report from the selectedReports list
          this.selectedReports = this.selectedReports.filter(id => id !== reportId);
        }
      } catch (error) {
        this.$toast.error(`Error: ${error.response?.data?.error || error.message}`);
      } finally {
        this.isUpdating = false;
      }
    }
  },
};
 

Compare user password during request

I’m getting a 404 not found error when trying to initiate a request by making the user input his password first, compare if it matches the password in the backend and then return the payload. It’s basically a get single item with id endpoint but with password as a request body.

enter image description here

Here’s my backend:

export const revealCard = async (req: Request, res: Response) => {
  const { cardId } = req.params;

  const { password } = req.body

  const userId = req.user?.userId;

  try {
    const user = await prismaClient.user.findUnique({
      where: { id: userId },
    });

    if (!user) {
      return res.status(404).json({
        error: true,
        message: "User not found.",
      });
    }

    // Compare the provided password with the user's password
    const isPasswordValid = await bcrypt.compare(password, user.password);

    if (!isPasswordValid) {
      return res.status(403).json({
        error: true,
        message: "Invalid password. Access denied.",
      });
    }

    // Proceed to retrieve the card only if the password is valid
    const card = await prismaClient.card.findUnique({
      where: { id: cardId },
    });

    res.json({
      card,
      message: "Card retrieved successfully!",
      error: false,
    });
  } catch (error) {
    console.error("Error retrieving event:", error);
    res.status(500).json({ error: true, message: "Internal server error" });
  }
};
import { Router } from "express";
import { revealCard } from "../controllers/card";

const cardRoutes: Router = Router();

cardRoutes.post("/reveal-card/:cardId", revealCard);

export default cardRoutes;

Here’s my frontend

export const cardAPI = createApi({
  reducerPath: "cards",
  baseQuery: axiosBaseQuery({ baseUrl: import.meta.env.VITE_BASE_URL }),
  tagTypes: ["Card"],
  endpoints: (builder) => ({
    revealCard: builder.mutation({
      query: ({ body, cardId }: { body: any; cardId: string }) => ({
        url: `card/reveal-card/${cardId}`,
        method: "POST",
        data: body,
      }),
      invalidatesTags: ["Card"],
    }),
  }),
});

export const { useRevealCardMutation } = cardAPI;
  const onSubmit = async (data: FormValues) => {
    try {
      const response = await revealCard({
        body: { password: data.password },
        cardId: item.id,
      }).unwrap();
  
      if (response) {
        toast.success("Authentication approved");
      }
    } catch (error) {
      const typedError = error as Error;
      toast.error(typedError.message);
    }
  };

what encoding does Chromium 126 show?

the script file contains Russian comments. Notepad shows UNICODE , i.e. UTF-8.

This encoding has been adopted since 1992. And it should replace all other anachronisms.

Here is the result of displaying this script file in the browser

const { numValue, unit } = getVolUnit("150px"); // �㘵匾煩棣菩銑觧菩� �箮解�郅郋赲��� �箮參���� 邽 �耨請解��� 

Question:

1. Which of the ancient encodings does Chromium 126 still use?

2. When will it end?

I dont know , what is encoding show browser.

The whole world should have switched to UNICODE for 22 years ago. I am waiting for Chromium representatives

JavaScript button to change image source not working

I have a set of buttons that each need to change an image to a different source, and show which one is selected (retain onclick appearance).

I want it to take the name of an element from a list and do things based on variables for that item, but mainly set the source and title.
script:

    const picList= {
      { "nature": { src: "nature.png", title: "" } }
      { "face":   { src: "face.png", title: "" } }
    };

    function changePic(picName) 
    {
      document.getElementById('currentPic').src = picList[picName].src;
      document.getElementById('currentPic').title = picList[picName].title;
    }

body:

<img id="currentPic" src="nature.png">
          <button onclick="changePic('face')" type="button">Face</button> 
          <button onclick="changePic('nature')" type="button">Nature</button> 

A lot of suggestions have me creating a const to hold the list item data, but that isn’t working and it should be the same to set each element right?

Now I only see the image it starts with, nature.png and onclick doesnt seem to do anything. I’m seeing some posts say it needs to return false but that isn’t working either.

Also, if I want the button to retain the onclick darker color until another button is clicked, where would be a good place to reset it when another button is clicked?

Need help for an interactive map on browser using three.js

I need help to modify the codes so that I can load data from a file .json and use the 2 drop-down menus, checkboxes and the search bar.
And I don’t want to use the API.

This is my map
https://expandersmap.altervista.org/

This the file .json
https://expandersmap.altervista.org/json_samples/expanders.json

And this is the map with 2 drop-down menus, check-box and search bar that I have difficulty implementing them in my map
https://map.canonn.tech/codex.html?hud_category=Geology&sub_class=Fumarole

Is there a way to pass a value from state without React keeping track of it?

I am working on a cart storage mechanism where I have a handleAddClicked function on a button. This function calls another addProductToCart function passed in a Context API instance.

addProductToCart takes in an object with an item, quantity, selectionIndices (main root of issue) and listIndex. selectionIndices is set through a state variable in the view.

I’m expecting the product to be passed to the addProductToCart function with the selectionIndices value at the time. But as soon as I add another object, all of the cart items change to the current selectionIndices value.

I believe this issue is stemming from the fact that I am passing the object with a reference to this.state.selectionIndices instead of a constant variable. In other words, maybe I am looking for a way to pass state byVal not byRef.

I know that the issue is not in the main addProductToCart function as hard-setting selectionIndices passed fixes this issue completely. Also, I’ve tried setting state into a temp variable and passing that but it doesn’t work either.

state = {
    product: {} as ProductType,
    selectionIndices: [] as number[]
}

handleAddClicked = () => {
    const ctx = this.context as CartContextType;
    const product = {product: this.state.product, quantity: 1, selectionIndices: this.state.selectionIndices, listIndex: ctx.cartItems.length};
        
    ctx.addProductToCart(product)
}

This bug has been driving me nuts! Any help would be greatly appreciated.

How can I add an error msg for This To-DO list problem

HTML

Add
“`
JS

function addTask(){
    if(inputBox.value === ''){
        document.getElementById("errmsg").innerHTML = "You Must Write Somthing!";
        return false;
    }
    else{
        let li = document.createElement("li");
        li.innerHTML = inputBox.value;
        listContainer.appendChild(li);
        let span = document.createElement("span");
        span.innerHTML = "&times;";
        li.appendChild(span);
    }
    inputBox.value = '';
    saveData();
}

I want to give an error in the placeholder, but it’s overwriting (https://i.sstatic.net/oT2UfccA.png) I’m new in JS, so I didn’t get how to fix it plz help me 🙁

GitLens VSCode extension not working for one particular file in my project otherwise its working fine?

I did not know why but for some reason GitLens not showing any visuals reviews on one particular file in the project.

Its working fine with other files except that file, I have already try toggle options, commit and pushed the code to github and tried changing modes as well but it is still not working on that file. Should I re-install the extension or is there is any solution for this problem.