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?

WebGL rendering incorrect on OffscreenCanvas

I am currently rendering using WebGL, but wanted to move to a worker to unblock the main thread.
Unfortunately, the rendered image changes when using an OffscreenCanvas, and i can’t find any reason why.

An an example, i used the MDN WebGL tutorial and tried to render it to an OffscreenCanvas.

Just by changing canvas.getContext("webgl") to canvas.transferControlToOffscreen().getContext("webgl"), the output changes (Same problem when using the OffscreenCanvas constructor, but i’m using this for simplicity in the example).
The image rendered to the OffscreenCanvas seems to be missing the rectangle drawn using drawArrays, but the background color changes, so WebGL did something.

I couldn’t find anything in the docs to indicate a behaviour change when rendering WebGL to an OffscreenCanvas, so i have no clue why this happens.

Tested on latest Chrome (141.0.7390.66) and Firefox (143.0.4).

https://jsfiddle.net/snv1xabt/1/

Best pattern for create vs edit form in React + Ionic Framework

I am creating an app and am using an Ionic modal to be able to open a view to input information, I am not using react form I am simply using input fields which I validate and onSubmit. I pull the data from a useState form and pass it on to the parent that calls the modal which then converts it into the datatype I need to display the information. I want to be able to use the view to also edit existing information. The wiring is a bit tricky and I am fairly new to react and Ionic. I don’t know much about patterns but I know there’s standards that should be followed with this type of behavior. I know the easiest route is to just create a new view for editing but the purpose of react is to reuse components. ChatGPT is helpful but also confusing me and making me get lost in details and going on tangents. Chat first proposed splitting openModal into openCreate and OpenEdit, and passing a mode and initialValue variable to the modal and tweak behavior accordingly. Then proposed using a small wrapper that calls a generic OpenModal with the initial values and input any other values necessary, I feel like a wrapper complicates things so I am attempting to do the first one. openEdit and createEdit gets a little confusing since the logic in the page is confusing. I am just a little lost if I am headed the right direction. Anyone have any advice?

import {
  IonButtons,
  IonButton,
  IonHeader,
  IonContent,
  IonToolbar,
  IonTitle,
  IonPage,
  IonItem,
  IonInput,
  useIonModal,
} from '@ionic/react';
import { OverlayEventDetail } from '@ionic/core/components';

const ModalExample = ({ dismiss }: { dismiss: (data?: string | null | undefined | number, role?: string) => void }) => {
  const inputRef = useRef<HTMLIonInputElement>(null);
  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonButtons slot="start">
            <IonButton color="medium" onClick={() => dismiss(null, 'cancel')}>
              Cancel
            </IonButton>
          </IonButtons>
          <IonTitle>Welcome</IonTitle>
          <IonButtons slot="end">
            <IonButton onClick={() => dismiss(inputRef.current?.value, 'confirm')} strong={true}>
              Confirm
            </IonButton>
          </IonButtons>
        </IonToolbar>
      </IonHeader>
      <IonContent className="ion-padding">
        <IonItem>
          <IonInput ref={inputRef} labelPlacement="stacked" label="Enter your name" placeholder="Your name" />
        </IonItem>
      </IonContent>
    </IonPage>
  );
};

function Example() {
  const [present, dismiss] = useIonModal(ModalExample, {
    dismiss: (data: string, role: string) => dismiss(data, role),
  });
  const [message, setMessage] = useState('This modal example uses the modalController to present and dismiss modals.');

  function openModal() {
    present({
      onWillDismiss: (event: CustomEvent<OverlayEventDetail>) => {
        if (event.detail.role === 'confirm') {
          setMessage(`Hello, ${event.detail.data}!`);
        }
      },
    });
  }

  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonTitle>Controller Modal</IonTitle>
        </IonToolbar>
      </IonHeader>
      <IonContent className="ion-padding">
        <IonButton expand="block" onClick={() => openModal()}>
          Open
        </IonButton>
        <p>{message}</p>
      </IonContent>
    </IonPage>
  );
}

export default Example;```

This is a snippet of what chat proposed for the first solution

    ``` const defaultForm: NewProjectForm = { name: "", totalHouses: 1, description: "" };
    
    const [presentCreate, closeCreate] = useIonModal(ProjectFormModal, {
      onDismiss: (d?: NewProjectForm | null, r?: string) => closeCreate(d, r),
      mode: "create",
      initialForm: defaultForm,
    });
    
    const currentFormRef = useRef<NewProjectForm>(defaultForm);
    
    const [presentEdit, closeEdit] = useIonModal(ProjectFormModal, {
      onDismiss: (d?: NewProjectForm | null, r?: string) => closeEdit(d, r),
      mode: "edit",
      // pass a ref so each open uses the latest value
      initialForm: currentFormRef.current,
      baselineForm: currentFormRef.current,
    });
    
    function openCreate() {
      presentCreate({ onWillDismiss: handleCreateDismiss });
    }
    
    function openEdit(project: ProjectCardProps) {
      currentFormRef.current = projectToForm(project);   // update ref first
      presentEdit({ onWillDismiss: (e) => handleEditDismiss(project.id, e) });
    }
    ```

Three viewports each with a different custom webfont in each. But both viewports display same font

I need to display multiple viewports on a single web page. I have 3 html viewports, each with a different custom webfont. [https://dev.clubtype.co.uk/viewports-my.html] Viewport 1 has the Normal font, viewport 2 has the Italic – so both belong the the same ‘font-family’. Whichever font is specified in viewport 2, it overwrites viewport 1 font. I run into the same issue whether employing, html+css, paragrah formatting or iframe.

Is there a way to prevent this overwriting?

 <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Custom Font Viewports</title>

  <style>
    /* Define custom fonts using @font-face */
    @font-face {
      font-family: 'Admark Std';
      src:  url('webfonts/AdmarkStd-Regular.woff2') format('woff2'),
        url('webfonts/AdmarkStd-Regular.woff') format('woff');
    }

    @font-face {
      font-family: 'Admark Std';
      src: url('webfonts/AdmarkStd-Italic.woff2') format('woff2'),
        url('webfonts/AdmarkStd-Italic.woff') format('woff');
    }

    @font-face {
      font-family: 'CustomFont3';
      src: url('fonts/CustomFont3.otf') format('opentype');
    }

    /* General styles for input viewports */
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 20px;
      background-color: #f4f4f4;
    }

    .viewport {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 20px;
      border: 2px solid #ccc;
      border-radius: 8px;
      background-color: #fff;
      width: 600px;
    }

    .viewport input {
      width: 100%;
      padding: 10px;
      margin-top: 10px;
      font-size: 36px;
      border: 1px solid #ddd;
      border-radius: 4px;
    }

    /* Apply custom fonts to specific viewports */
    .viewport.font1 input {
      font-family: 'Admark Std', serif;
    }

    .viewport.font2 input {
      font-family: 'Admark Std', serif;
    }

    .viewport.font3 input {
      font-family: 'CustomFont3', sans-serif;
    }
  </style>
</head>
<body>
  <div class="viewport font1">
    <label for="input1">Custom Font 1:</label>
    <input type="text" id="input1" placeholder="Type here...">
  </div>

  <div class="viewport font2">
    <label for="input2">Custom Font 2:</label>
    <input type="text" id="input2" placeholder="Type here...">
  </div>

  <div class="viewport font3">
    <label for="input3">Custom Font 3:</label>
    <input type="text" id="input3" placeholder="Type here...">
  </div>
</body>
</html>

calculator result -my result contains extra number(my second number)

i am writing a calculator with javascript,when i want to display result of calculation the result contains extra number (my second number is showing beside the result).the result contains result+secnum

let memory = document.getElementById('memory');
let num = document.getElementById('inp-num');
let firstnum = 0;
let secnum = 0;
let operand = '';
let result = 0;

let numbutt = document.querySelector('#numbers');
numbutt.addEventListener('click', (event) => {
  let target = event.target;
  switch (target.value) {
    case '1':
      num.value += '1';
      break;
    case '2':
      num.value += '2';
      break;
    case '3':
      num.value += '3';
      break;
    case '4':
      num.value += '4';
      break;
    case '5':
      num.value += '5';
      break;
    case '6':
      num.value += '6';
      break;
    case '7':
      num.value += '7';
      break;
    case '8':
      num.value += '8';
      break;
    case '9':
      num.value += '9';
      break;
    case '0':
      num.value += '0';
      break;
    case '.':
      num.value += '.';
      break;
  }
})

let opbutt = document.querySelector('.ver-op');
opbutt.addEventListener('click', (event) => {
  let target = event.target;
  switch (target.value) {
    case '*':
      firstnum = num.value;
      operand = '*';
      memory.textContent = firstnum + operand;
      num.value = '';
      break;
    case '-':
      firstnum = num.value;
      operand = '-';
      memory.textContent = firstnum + operand;
      num.value = '';
      break;
    case '+':
      firstnum = num.value;
      operand = '+';
      memory.textContent = firstnum + operand;
      num.value = '';
      break;
    case '/':
      firstnum = num.value;
      operand = '/';
      memory.textContent = firstnum + operand;
      num.value = '';
      break;
  }
})

let eq = document.querySelector('.equal');
eq.addEventListener('click', (event) => {
  secnum = num.value;
  result = 0;
  memory.textContent = (firstnum) + operand + (secnum);
  if (operand == '/') {
    result = Number(firstnum) / Number(secnum);
    num.value = num.value.toFixed(2);
  } else if (operand == '*') {
    result = Number(firstnum) * Number(secnum);
  } else if (operand == '+') {
    result = Number(firstnum) + Number(secnum);
  } else if (operand == '-') {
    result = Number(firstnum) - Number(secnum);
  }
  num.value = result;
  
  firstnum = result;
})

let clear = document.querySelector('.clearbutt');
clear.addEventListener('click', (event) => {
  firstnum = '';
  secnum = '';
  operand = '';
  num.value = '';
  memory.textContent = '';
})

let calckey = document.getElementById('calc-container');
calckey.addEventListener('keypress', (event) => {
  if (event.key === 'Enter') {
    secnum = num.value;
    result = 0;
    if (operand === '/') {
      result = Number(firstnum) / Number(secnum);
    } else if (operand === '*') {
      result = Number(firstnum) * Number(secnum);
    } else if (operand === '+') {
      result = Number(firstnum) + Number(secnum);
    } else if (operand === '-') {
      result = Number(firstnum) - Number(secnum);
    }
    num.value = result;
    memory.textContent = (firstnum) + operand + (secnum);
    firstnum = result;
  }
})
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>online-calculator</title>
  <link rel="stylesheet" href="/style.css">
  <script src="/calculator.js" defer></script>
</head>

<body>
  <div id="calc-container">
    <div id="calulation">
      <p id="memory"></p>
      <input type="text" name="inptext" class="inp" id="inp-num" readonly>
    </div>
    <div id="hor-op">
      <div class="left-side">
        <button class="horop-but">%</button>
        <button class="horop-but">CE</button>
        <button class="horop-but clearbutt">C</button>
        <button class="horop-but"><sup>1 </sup> / <sub>x</sub></button>
        <button class="horop-but">x<sup>2</sup></button>
        <button class="horop-but">√</button>
      </div>
      <div class="right-side">
        <button class="horop-right-but " value="cls"><img src="/icons8-rewind-button-round-50.png" alt=""></button>
        <button class="horop-right-but equal" value="=">=</button>
      </div>


    </div>
    <div id="main">
      <div id="numbers">
        <button class="butt num-but" value="1">1</button>
        <button class="butt num-but" value="2">2</button>
        <button class="butt num-but" value="3">3</button>
        <button class="butt num-but" value="4">4</button>
        <button class="butt num-but" value="5">5</button>
        <button class="butt num-but" value="6">6</button>
        <button class="butt num-but" value="7">7</button>
        <button class="butt num-but" value="8">8</button>
        <button class="butt num-but" value="9">9</button>
        <button class="num-but">+/-</button>
        <button class="butt num-but" value="0">0</button>
        <button class="butt num-but" value=".">.</button>
      </div>
      <div class="ver-op">
        <button class="verop-but " value="*">*</button>
        <button class="verop-but " value="-">-</button>
        <button class="verop-but " value="+">+</button>
        <button class="verop-but " value="/">/</button>
      </div>
    </div>
  </div>
</body>

</html>

for example : 8 * 5 =40 but my result is 405.second number is joining my result number.
it happens just when i am using keypress event.
while i am using by click event it is working

My site is not eligible for PayPal JS SDK

I’m writing a nextjs app, currently debugging it on localhost.
I want to have inputs for card details using PayPal JS SDK, so I just the card-fields component.

However cardFields.isEligible() returns false. If I tried to render the NameField any I get an exception clientID prop not defined. I’m using a sandbox app id.

Here’s the react component

export default function PayPalClient() {
  const onScriptLoad = () => {
    const cardFields = window.paypal.CardFields({});

    if (cardFields.isEligible()) {
      cardFields.NameField().render(document.getElementById("card-name-field-container"));
    }
    else {
      console.log('not eligible');
    }
  }

  return (
    <div>
      <Script
        src={`https://www.paypal.com/sdk/js?client-id=${CLIENT_ID}&components=card-fields`}
        strategy="afterInteractive"
        crossOrigin="anonymous"
        onLoad={onScriptLoad}
      />
      {/* Testing just the card name field right now */}
      <div id="card-name-field-container" />
    </div>
  );
}

What am I doing wrong?

Why do I need to select an option from this ReactJS drop-down menu twice for the change to register?

I am working with an application that has a Java backend, utilising the Play Framework, and a ReactJS frontend. One of the pages contains a form where user data can be edited and it has a drop-down menu whose values are populated from the backend, based on that user’s database information. Let’s imagine the three values in range are Employed, Unemployed, Temporarily_Employed. If a user is in the system as Employed then that should be selected as the default in the drop-down menu.

The problem I am experiencing is that, when first interacting with the drop-down, even if I choose another option from the list (eg: Unemployed) the change is not registered and the default option is still selected. This does not happen if I select from the drop-down a second or further time – it works fine then.

<FormSelect
    id="employmentStatus"
    name="theName"
    label="theLabel"
    options= // the statuses in range, eg: Employed, etc
    selected={this.state.employmentStatus} //This seems to be where the trouble begins - I populate it initially with whatever the appropriate value is in the user's record in the DB
    onChange={this.handleEmploymentStatusChange}
    hasEmptyDefault={!this.state.employmentStatus}
/>


export default class EmploymentStatusPage extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            name,
            email, 
            employmentStatus
        }
    }
}

handleEmploymentStatusChange = newValue => {
    this.setState({
        employmentStatus: newValue
    })
}

In Angular, a awaited method call, kicks you out of the NgZone. Why?

When you do a simple call like await Promise.resolve() inside an Angular component, the code below that call will not be inside the zone anymore.

The easiest way to reproduce this is to create a component and write this into any method:

console.log('Inside Angular zone?', NgZone.isInAngularZone()); // => true
await Promise.resolve();
console.log('Inside Angular zone?', NgZone.isInAngularZone()); // => false

(Done in this stackblitz)

Why is that the case?

As long as i don’t use e.g. zone.runOutsideAngular() i don’t expect to be kicked out.