JavaScript library not working correctly when not added as script on page that it is being used on

I want to use an implementation of Ion JavaScript library in my Java application with a JSP frontend.

If I add:

<script type="text/javascript" src='<c:url value="https://path/to/library/assets/ion/v6/stable/extensions/require/loader.js"/>?_=<c:url value="${cacheBuster}"/>'></script>

to the JSP page I’m looking to use it on, the below feature works correctly and I can see the library in the page sources in my Developer Tools.

<div class="m-card m-card-notification m-card-notification--warn" role="status" data-module="m-card-close" data-notification-description="close icon">
    <div class="m-card-content">
        <div class="m-card-content__inner">
            <p>Some text here.</p>
        </div>
    </div>
</div>

Long term, however, I may wish to use this library in different parts of the UI, so I’d like to place this in a more suitable location. Again, when I load the page, can see the library in the page sources in my Developer Tools but the ‘X’ icon that should appear and hide the div if clicked does not load. It should appear with the addition of data-module="m-card-close" Do I need to include the <script> above in every page I want to use some feature from this library or is there a cleaner way to do this?

Can a backend using Multer for file uploads recognize an image sent as a byte[] in the request?

In a B/S architecture system, the backend is written in Node.js and uses Multer to handle file uploads, and the frontend is an Android application written in Java. If the frontend gets photo data from the camera as a byte[] (YUV), transforms it to JPEG form’s byte[], wraps it to multipart/form-data, and sends it to the backend, can Multer correctly recognize this uploaded file and save the picture successfully?

The code in Android is like this:

public void login(String account,, byte[] photoYUVBytes, final LoginCallback callback) {
        RequestBody accountBody = account != null ? RequestBody.create(MediaType.parse("text/plain"), account) : null;
        MultipartBody.Part photoPart = null;
        if (photoYUVBytes != null) {
            Camera.Size size = MainFragment.getPreviewSize();
            byte[] photoBytes = yuvToJpeg(photoYUVBytes,size.width,size.height);
            RequestBody photoBody = RequestBody.create(MediaType.parse("image/*"), photoBytes);
            photoPart = MultipartBody.Part.createFormData("photo", "face.jpg", photoBody);
        }

        Call<LoginResponse> call = loginApi.login(accountBody, photoPart);
        call.enqueue(new Callback<LoginResponse>() {
            @Override
            public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    callback.onSuccess(response.body());
                } else {
                    callback.onError(...);
                }
            }
        });
    }

and the backend code is like this:

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads/'); // store catalog
    },
    filename: function (req, file, cb) {
        const ext = path.extname(file.originalname) || '.jpg'; 
        cb(null, `${Date.now()}${ext}`);
    }
});
const upload = multer({ storage: storage });
router.post("/login", upload.single("photo") , async (req, res) => {...}

React + Vite + React Helmet: Dynamic meta tags not showing correctly when sharing on WhatsApp

I’ve built a React project using Vite, and I’m working on improving SEO and link previews.
I’m using React Helmet to dynamically update the meta title and description based on the current route. When I check in the browser, the title and meta tags update correctly in the dev tools.
However, when I share the link on WhatsApp (or any social media), the preview always shows my home page’s title and description, not the ones set for the specific route.

I’ve added all the required Open Graph tags, but it still doesn’t work.

Verified meta tags in browser (they update dynamically)

Added og:title, og:description, og:image, and og:url

Used React Helmet

Deployed the app (so it’s not a localhost issue)

I want to make casual school calendar web site [closed]

I’m making school calendar web site.
but web site design isn’t perpect in my mind.
I want to change web design.
but I don’t know how change web design.
can you advise mt web site design

this is my first web site design
but this design is dull in color
thus I want to change color of web site and ui
this is my second web site design
I changed color of web site but this isn’t perpect my mind and I don’t know changing ui

Using embedded youtube playlist index to cycle through array

I have a youtube playlist embedded in an iframe and was hoping to use the playlist index to cycle through an array of titles on-screen (i.e. when the next video starts playing, the next item in the array will show). Is this possible? What am I doing wrong? Apologies in advance because I’m very new to JS… this might be gibberish but I felt like I was on to something.

var myArray = ["song 1", "song 2"];

var player;
  function onYouTubePlayerAPIReady() {
    player = new YT.Player('video', {
        events: {
            'onReady': onPlayerReady
        }
    });
}

 function onPlayerReady(event) {
    console.log(Array.from(document.querySelectorAll('.ytd-playlist-video-list-renderer #video-title')).map((el) => {return el.textContent.trim()}).sort().join("n"))

  var Number = 
function(){
     player.getPlaylistIndex();
};
  var print = document.getElementById('print');
print.innerHTML = myArray[Number];
    }

Mathematical expressions not rendering properly in chat widget with marked.js and KaTeX – Need all math formatted

I’m building a Q&A chat widget that uses marked.js for Markdown rendering and KaTeX for mathematical expressions. The backend returns LaTeX-formatted math, but it’s displaying as raw text instead of properly rendered equations. I need all mathematical expressions to be properly formatted, regardless of how they’re delimited in the source.

Current Behavior

The AI response comes back with LaTeX math like this:

The symbol pm indicates that there are generally two solutions...
The term b^2 - 4ac is known as the discriminant...
If b^2 - 4ac > 0: Two distinct real roots.
If b^2 - 4ac = 0: One real root (a repeated root).
If b^2 - 4ac < 0: No real roots (the roots are complex).

Instead of properly rendered math symbols (±, b²-4ac, >, =, <), I see the raw LaTeX code as plain text.

Expected Behavior

All math expressions should render as formatted equations using KaTeX:

  • pm should render as ±
  • b^2 – 4ac should render as b²-4ac with proper superscripts
  • All mathematical operators and expressions should be beautifully formatted
  • Both inline and display math should work seamlessly.

Relevant Code

HTML Setup:

<!-- KaTeX CSS and JS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/contrib/auto-render.min.js"></script>

<!-- Markdown parser -->
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>

JavaScript rendering function:

function renderMath(element) {
  if (window.renderMathInElement) {
    renderMathInElement(element, {
      delimiters: [
        {left: '$$', right: '$$', display: true},
        {left: '$', right: '$', display: false},
        {left: '\[', right: '\]', display: true},
        {left: '\(', right: '\)', display: false},
        {left: '[ ', right: ' ]', display: true},
        {left: '[', right: ']', display: true}
      ],
      throwOnError: false,
      ignoredTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'],
      processEscapes: true
    });
  }
}

Message appending function:

function appendMessage(text, from) {
  window.chatBuffer.push({ text, from });
  if (window.chatBuffer.length > 50) window.chatBuffer.shift();

  const wrap = document.createElement("div");
  wrap.className = `message ${from}`;
  const bubble = document.createElement("div");
  
  if (text.startsWith('Selected subject:') || text.startsWith('Welcome!')) {
    bubble.className = "subject-notification";
    bubble.textContent = text;
  } else {
    bubble.className = "bubble";
    
    if (from === "model") {
      bubble.innerHTML = marked.parse(text);
      
      // Render math expressions after DOM insertion
      setTimeout(() => {
        renderMath(bubble);
      }, 10);
    } else {
      bubble.textContent = text;
    }
  }

  wrap.appendChild(bubble);
  messagesEl.appendChild(wrap);
  messagesEl.scrollTop = messagesEl.scrollHeight;
}

How can I ensure ALL math expressions are properly formatted?

Passing bytes into chainlink functions response

I am returning the bytes encoded value for the uint256 from my server but struggling to understand how to pass this onto the response. I have used the BigInt default javascript function right now as it has a default constructor using a hex string based argument and then using Functions.encodeUint256 to return the response value but was wondering if there’s any other way to do this.
Here is the code snippet I used:(https://i.sstatic.net/Dj1bqu4E.jpg)

I also tried the Uint8Array but it does not seem to have the hex based constructor in the playground so I was wondering how to pass a hex bytes string just as it is, similar to the ethers.getBytes function.

Why is the return statement in my express.js route not stopping execution of the middleware that is placed after it?

The return statement in /routes/todos.jsz is not stopping the execution of my app. Instead, the the “Handle 404 Errors” app.use() function that is placed after app.use("/todos", todoRoutes) is being executed. When I visit the route localhost:3001/todos/addTodo the correct response is being displayed “Thanks for submitting the form”, but in my console, the console.error() call from the bottom of app.js is being displayed with an error stack, BUT the return statement in the generic handler is NOT being returned to the user.

Why is my app continuing on to the 404 handler even though I return res.send() in my route? I don’t think this is happening in my other apps.

app.js

"use strict";

const express = require("express");
const cors = require("cors");
const helmet = require("helmet");
const { NotFoundError } = require("./expressError");
const todoRoutes = require('./routes/todos')

const app = express();

app.use(cors());
app.use(helmet({ crossOriginResourcePolicy: false }));
app.use(express.json());

app.use("/todos", todoRoutes)

// so we don't get the "not found" error in our console for the favicon
app.get("/favicon.ico", (req, res) => res.sendStatus(204));

// our home page of our backend, just send back a 200 response
app.get("/", (req, res) => res.sendStatus(200));

/** Handle 404 errors -- this will catch everything that makes it this far */
app.use(function (req, res, next) {
  console.log("hit the 404 use".brightCyan)
  return next(new NotFoundError());
});

/** Generic error handler; anything unhandled goes here. */
/** express knows that a function is an error handler because
 * the function has 4 parameters */
app.use(function (err, req, res, next) {
  console.log("hit the generic use".brightCyan)
  if (process.env.NODE_ENV !== "test") console.error(err.stack);
  const status = err.status || 500;
  const message = err.message;

  console.log(status, message)

  return res.status(status).json({
    error: { message, status },
  });
});

module.exports = app;

routes/todos.js

const express = require('express');
const router = express.Router();

router.get('/addTodo', async function (req, res) {
  console.log('==> running todo route'.brightCyan);
  return res.send("Thanks for submitting the form");
})

module.exports = router;

How to Trigger an Elementor Off-Canvas Element with a Custom Animated Button (html/ CSS/ JS)?

I am learning web programming and recently encountered a problem.

I am using WordPress v6.8.3 and Elementor Pro 3.32.2.

I would like to use a manually created animated hamburger menu button to trigger another element, an Off-canvas created with Elementor’s native off-canvas widget to show up.

The animated button itself wasn’t a problem. Let’s assign this button element the ID “nav-icon1” Here’s the code for an HTML widget:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Animated Navigation Icon</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

  <style>
    * {
      margin: 0;
      padding: 0;
    }

    /* Icon 1 */
    #nav-icon1 {
      width: 60px;
      height: 45px;
      position: relative;
      margin: 50px auto;
      transform: rotate(0deg);
      transition: .5s ease-in-out;
      cursor: pointer;
    }

    #nav-icon1 span {
      display: block;
      position: absolute;
      height: 9px;
      width: 100%;
      background: #d3531a;
      border-radius: 9px;
      opacity: 1;
      left: 0;
      transition: .25s ease-in-out;
    }

    /* Adjust the position of the spans for icon 1 */
    #nav-icon1 span:nth-child(1) {
      top: 0px;
    }

    #nav-icon1 span:nth-child(2) {
      top: 18px;
    }

    #nav-icon1 span:nth-child(3) {
      top: 36px;
    }

    #nav-icon1.open span:nth-child(1) {
      top: 18px;
      transform: rotate(135deg);
    }

    #nav-icon1.open span:nth-child(2) {
      opacity: 0;
      left: -60px;
    }

    #nav-icon1.open span:nth-child(3) {
      top: 18px;
      transform: rotate(-135deg);
    }
  </style>
</head>
<body>

  <!-- Navigation Icon 1 -->
  <div id="nav-icon1">
    <span></span>
    <span></span>
    <span></span>
  </div>

  <script>
    $(document).ready(function(){
      // Toggle the 'open' class on nav icon 1 when clicked
      $('#nav-icon1').click(function(){
        $(this).toggleClass('open');
      });
    });
  </script>

</body>
</html>

By inserting this code into the Elementor Pro HTML widget, you’ll get a button that changes its form on click and reverses back on the second click.

Now comes the difficult part.

I can’t find any information on how to trigger the off-canvas element (Off-Canvas Name: “offcanvastestelement“) by clicking the manually created button (button ID: “nav-icon1“).

I tried inspecting the source code of Elementor Pro, but unfortunately, I’m not that experienced in JS yet.

Could you please help me with this, if it’s even possible to achieve?

Modern JavaScript and String Substition [duplicate]

Does JavaScript have a native method for substituting values into an existing string? For example:

var [a, b, c] = ['apple', 'banana', 'cherry'];
var s = 'I have an %s with a %s and a %s';
//  substitute variables?

JavaScript has the template literal:

var [a, b, c] = ['apple', 'banana', 'cherry'];
var result = `I have an ${a} with a ${b} and a ${c}`;

and console.log() has:

var [a, b, c] = ['apple', 'banana', 'cherry'];
var s = 'I have an %s with a %s and a %s';
console.log(s, a, b, c);

The template literal allows me to store the result in a variable, but it’s only for a new string literal; as far as I am aware, you can’t apply the substitution to an old string. The console.log() method can substitute into an existing string, but, as far as I’m aware, only outputs to the console, and not into a variable.

I can, of course, write my own function:

function sprintf(string, ...values) {
    values.forEach(v => {string = string.replace('%s', v)});
    return string;
}
var [a, b, c] = ['apple', 'banana', 'cherry'];
var s = 'I have an %s with a %s and a %s';
var result = sprintf(s, a, b, c);
console.log(result);

Is there a native method in JavaScript which does the same thing?

The sample is trivial, but the rationale is that I want to define some strings earlier int he code to be substituted multiple times later. Template literals require me to redefine the string each time, which is less organised.

jest object in setupFilesAfterEnv differs from jest in test files

I’m trying to add a custom method onto the Jest API inside a setup file (config.ts) configured via setupFilesAfterEnv. However, the jest object I mutate in the setup file is NOT the same reference as the jest object visible inside my test files.

As a result, a property I define (jest.toto) is missing in the spec, and a direct reference comparison shows the objects are different.

In setup (test/config.ts):

(jest as any).toto = 'toto';
(global as any).jestCopy = jest;

In test file (*.spec.ts):

console.log((global as any).jestCopy.toto) → exists
console.log(jest.toto) → undefined
console.log((global as any).jestCopy === jest) → false

multer.memoryStorage() file undefined or Error: unexpected end of form

I’m trying to upload a file to the OpenAI API using Firebase Cloud Functions, Express and Multer. I have a React UI that I’m using to upload a file to my backend to then send to the OpenAI API, but I’m stuck on an issue with Multer. Whenever I try to upload a file through my React UI the backend/multer either doesnt receive it or errors out saying “Error: unexpected end of form.” My backend code is the following:

import {onRequest} from "firebase-functions/v2/https";
import express from "express";
import cors from "cors";
import multer from "multer";

const app = express();
app.use(cors({origin: true}));
app.use(express.json());
app.use(express.urlencoded({extended: true}));

// Multer memory storage
const storage = multer.memoryStorage();
const upload = multer({storage: storage});

// Healthcheck endpoint
app.get("/healthcheck", (req, res) => {
  res.status(200).json({
    status: "ok",
    timestamp: new Date().toISOString(),
    message: "Backend is running",
  });
});

// Parse file endpoint
app.post("/parse-file", upload.single("uploadFile"), async (req, res) => {
  console.log("Content-Type:", req.headers);
  console.log("File received:", req.file);
  console.log("Body:", req.body);
  res.json({ok: true, body: req.body});
  return;
});

export const api = onRequest(app);

If I use the most recent stable version of Multer, I always see the “Error: unexpected end of form.” If I use Multer v1.4.2 or v1.4.3, the api returns {ok: true, body: {}} saying the file was undefined. Additionally, any other fields that I pass to the endpoint do not show up either (like a username or test field, the body is still always empty).

I’ve tried moving around the app.use(express.json()) line. I’ve tried using Busboy as well which returns the “Error: unexpected end of form”. When I ask AI tools for help, they suggest ensuring the field name in the line upload.single("uploadFile") matches which I’ve checked. I’ve tried different versions of Firebase functions as well which didnt change the result. I’ve tried hitting the endpoint manually through Postman and not my UI but I got the same results back. Based on that I’m assuming it’s not a CORS issue but at this point anything is possible haha. If anyone has any suggestions that would be super helpful!

How to add top toolbar to lightweight charts chart?

This is the chart component:

import { ColorType, createChart, CrosshairMode } from "lightweight-charts";
import { useEffect, useRef, useState } from "react";

export default function Chart({ data, type, symbol, height = 700 }) {
  const chartContainerRef = useRef();
  const [pointData, setPointData] = useState({});
  useEffect(() => {
    const chart = createChart(chartContainerRef.current, {
      layout: {
        background: { type: ColorType.Solid, color: "#000000" },
        textColor: "#ffffff",
      },
      width: chartContainerRef.current.width,
      height,
      autoSize: true,
      grid: {
        vertLines: {
          visible: false,
        },
        horzLines: {
          visible: false,
        },
      },
      crosshair: {
        mode: CrosshairMode.Magnet,
      },
      timeScale: {
        backgroundColor: "#3b3b3b",
        timeVisible: true,
        rightBarStaysOnScroll: true,
      },
    });
    chart.timeScale().fitContent();
    const series = updateChartSeries(chart, type, data);
    chart.subscribeCrosshairMove((param) => {
      setPointData(param.seriesData.get(series));
    });
    return () => {
      chart.remove();
    };
  }, [data, height, type]);
  return (
    <div className="mt-4 ms-2 me-2 chart">
      <Legend pointData={pointData} symbol={symbol} />
      <div ref={chartContainerRef}></div>
    </div>
  );
}

which results in the below:

chart

How to add the upper toolbar shown here? The documentation is missing that information.

This is what I’m interested in:

toolbar

Is there a way to add it by passing an option / flag or should I resort to hacking to achieve this?