Prevent HTML string rendering

I’m building an array of small HTML snippets. Javascript stores them just fine, but when I attempt to retrieve them nothing is returned. I’m told by the AI bots that is because javascript is attempting to render them?! even though they’re not associated with an innerHTML. How do I prevent this behavior? Why does it not do this on storing but only on retrieving?

I’ve tried removing the html ‘<‘ characters with a RE, but would much prefer a better approach,

Bing Maps API – Pushpin in wrong Position?

How come my pushpin location is constantly appearing down and right to where I’m actually clicking?

I have my context menu appearing at the correct location but the tryPixelToLocation is giving me a point down and right to where I’m actually clickin. Not sure why.

Please advise. Thanks.

For project requirements I can’t use the window.Microsoft.Maps.addHandler. I have to do my actions through the context menu

import React, { useState, useEffect, useRef } from 'react';

const BingMap = ({ bingMapsKey }) => {
    const mapRef = useRef(null);
    const [menuPosition, setMenuPosition] = useState({ x: '0px', y: '0px' });
    const [showMenu, setShowMenu] = useState(false);
    const [map, setMap] = useState(null); // State to hold the map object

    useEffect(() => {
        const script = document.createElement('script');
        script.type = 'text/javascript';
        script.async = true;
        script.defer = true;
        script.src = `https://www.bing.com/api/maps/mapcontrol?callback=loadMapScenario&key=${bingMapsKey}`;
        document.body.appendChild(script);

        window.loadMapScenario = () => {
            const newMap = new window.Microsoft.Maps.Map(mapRef.current, {
                center: new window.Microsoft.Maps.Location(47.6062, -122.3321),
                zoom: 10
            });

            mapRef.current.addEventListener('contextmenu', handleContextMenu);
            setMap(newMap); // Set the map object in state

            return () => {
                mapRef.current.removeEventListener('contextmenu', handleContextMenu);
            };
        };

        return () => {
            if (script.parentNode) {
                script.parentNode.removeChild(script);
            }
        };
    }, [bingMapsKey]);

    const handleContextMenu = (event) => {
        event.preventDefault();
        const mapContainer = mapRef.current.getBoundingClientRect(); 
        setShowMenu(true);

        setMenuPosition({
            x: (event.clientX - mapContainer.left) + 'px',
            y: (event.clientY - mapContainer.top) + 'px'
        });
    };
    
    const handleMenuClick = (action, x, y) => {
        if (!map) return;


        switch (action) {
            case 'add':
                //Convert pixel coordinates to map location
                const clickLocation = map.tryPixelToLocation(new window.Microsoft.Maps.Point(
                    parseInt(x ),
                    parseInt(y)
                ));
    
                let pinTitle = prompt("Enter a title for the pin:", "New Location");
                let pinDescription = prompt("Enter a description for the pin:", "");
    
                if (pinTitle !== null) {
                    const pin = new window.Microsoft.Maps.Pushpin(clickLocation, {
                        title: pinTitle,
                        subTitle: pinDescription
                    });
    
                    pin.metadata = {
                        title: pinTitle,
                        description: pinDescription
                    };
    
                    map.entities.push(pin);
                }
                break;
    
            case 'edit':
                console.log('EDIT');
                // Handle edit pin action
                break;
            case 'remove':
                console.log('REMOVE');
                // Handle remove pin action
                break;
            default:
                break;
        }
        setShowMenu(false);
    };
    

    return (
        <div style={{ position: 'relative' }}>
            <div ref={mapRef} style={{ width: '100vw', height: '100vh' }}></div>
            {showMenu && (
                <div
                    style={{
                        position: 'absolute',
                        left: menuPosition.x,
                        top: menuPosition.y,
                        background: 'white',
                        border: '1px solid black',
                        padding: '5px',
                        zIndex: 1000
                    }}
                >
                    <button onClick={() => handleMenuClick('add', menuPosition.x, menuPosition.y)}>Add Pin</button>
                    <button onClick={() => handleMenuClick('edit', menuPosition.x, menuPosition.y)}>Edit Pin</button>
                    <button onClick={() => handleMenuClick('remove', menuPosition.x, menuPosition.y)}>Remove Pin</button>
                </div>
            )}
        </div>
    );
};

export default BingMap;

Is it possible to read a json file from a url in JavaScript, if so, how?

I have a JSON file hosted at https://soap-api.w3spaces.com/data/FrontPageData.json, and I want to be able to access it in html. E.g. I want a specific element to show a specific value in the json file. I know how to do that, but I don’t know how to read the file in JavaScript in the first place. I also don’t know if it’s even possible lol. If someone knows how then please let me know 🙂

I’ve tried fetch() but that just outputs “unable to fetch”.
I’ve tried other ways I found on the internet but I don’t think they were actually supposed to help my problem, so of course they didnt.

How do I layer SVG files on top of each other in CSS?

Question: How do I position my SVG files on top of each other and still be able to animate them? I have three separate SVG graphics that when layered directly on top of each other they create a logo. The SVG graphics were created in Illustrator and their individual artboards/viewport are aligned, I just need to layer them on top of each other in the CSS.

To achieve the layering in CSS I am currently using .logo{position: relative;} .logo img{position: absolute ;top:0;left:0;}. In my HTML I have an onclick function that triggers an @keyframe animation that rotates the “face .svg” when the user clicks on it. However because I am using position: absolute in the CSS the animation is not playing.

I have tried positioning the SVGs manually using left, right, bottom, and top, however I don’t want to guess their positioning, it needs to be exactly like in the Illustrator file to recreate the logo. Can anyone help me position my SVG graphics while still being able to animate them?

I posted the code below and here is a link to the website so you can see the SVG graphics.
https://ilikeacode.github.io/Face-Rotate/
When you click on the smiley face it is supposed to rotate, but it doesn’t.

function animateFace() {
  document.getElementById("face").style.animationPlayState = "running";
}
/* I believe .logo img{position: absolute;} is preventing the face from rotating. 
*/ 
.logo{
  position: relative;
}

.logo img{
  position: absolute;
  top:0;
  left:0;
}

#face{
  animation:rotate 5s; 
  cursor: pointer;
  animation-play-state: paused;
}


@keyframes rotate {
  100% {transform: rotate(360deg);}
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Rotate Face</title>
  <link rel="stylesheet" href="styles.css">
</head>

<body>
<div class="logo">

<img class="happy" src="assets/happy.svg" width="150px">

<img id="face"onclick="animateFace()"src="assets/face.svg" width="150px">

<img class="smile" src="assets/smile.svg" width="150px">

</div>
  

  <script src="index.js"></script>

</body>

</html>

strong text

How to change positioning of all child elements (and their child elements) to absolute while still keeping thier original location?

i’m working on a document editor of sort, basically

user uploads PDF => server converts to html => frontend renders html to editor => user edits => server convert the html back to pdf

issue is, when a user changes size / delete an element in the #editor div, elements below that get pushed up.

so i want to change all the element to absolute, while still keeping their postioning

function prepareDocument() {
    $("#editor").find("*").each(function () {
        $(this).attr('contenteditable', true);
        // Make $(this) absolute while keeping original positioning
    });

    $('#editor').find('img').on('dblclick mousedown mouseup', function (event) {
        event.preventDefault();
        event.stopPropagation();
        $(this).focus();
    });

    disableDragGlobally();
}

any help will be greatly appricated!! can be in either jQuery or vanila js

tried to straight up change to absolute or try to play with offset, didnt help

References in MongoDB

I have an app where one document wants to reference another document, the catch here is the other documents could be in two different collections. is there a way to do it, keeping in mind I’m going to have to populate them when they are fetched.

const schemaOne = new Schema({
   name: string,
// other fields
})

const schemaTwo = new Schema({
   name: string
// other fields
})

const schemaThree = new Schema({
// I want to reference a document from schemaOne or two in one field
   someId: ObjectId,
})

The solution I’m not try to do is to create two fields one for the schemaOne and the other for schemaTwo. but this I think will create more complexity.

index.js:683 Uncaught Error: Page “/[[…slug]]/page” is missing param “/” in “generateStaticParams()”

I am going to merge the react website with the next.js website and getting title error in console and terminal this is the error “index.js:683 Uncaught Error: Page “/[[…slug]]/page” is missing param “/” in “generateStaticParams()”, which is required with “output: export” config.
at DevServer.renderToResponseWithComponentsImpl (file://F:NEXT.JSvpatomicnode_modulesnextdistserverbase-server.js:1032:27)”

this is what I followed a document Migrating from Create React App in react src folder I created a app folder In app folder i created layout.js and [[…slug]] folder in [[…slug]] folder created client,js and page.js file
this is client.js file

import React from "react";
import dynamic from "next/dynamic";

const App = dynamic(() => import("../../App"), { ssr: false });

export function ClientOnly() {
  return <App />;

and here is the page,js file

import "../../index.css";
import { ClientOnly } from "./client";

export function generateStaticParams() {
  return [{ slug: [""] }];
}

export default function Page() {
  return <ClientOnly />;
}

I need to solve this error

Embed code in Webflow – CSS is not working with JavaScript

I just created my own slider and successfully connected with Webflow html div elements.
All works perfectly except this line of code

.nav-buttons button.active .selected-block { background-color: #14aed2; transition: background-color 0.3s ease; }

this selected-block css styling working but when my button is active this selected-block div inside my button dont change color.

I don’t know it’s something wrong in css code (this codes are tested in codpen.io) and working perfectly but in Webflow published site just active button style don’t.

If anyone had anyone same problem and sucesfully find solution I would be more then happy to hear it.

Best

Oh! I forget mention code is embed element should I use it in head section?

I’m using as embed code in this Webflow created div element

How can I get the current frame of an HTML video as a JavaScript array?

On the press of a button, I would like to convert the current video frame from the webcam to an array or tfjs tensor.

I am unable to find a way to:

  • Get the array
  • Crop and resize the array to the largest possible 64x64x3 image

I would like to use/implement some functions (getFrameFromVideo and crop_to_size) that can do something along the lines of the following:

const video = document.getElementById("cam");
var arr_frame;
var cropped_frame;
var tensor_frame;

function crop_to_size(img, xsize, ysize) {
  // crop the image
  return cropped_img;
}

function predict_img() {
  arr_frame = getFrameFromVideo(video);
  cropped_frame = crop_to_size(arr_frame, 64, 64);
  tensor_frame = tf.tensor(cropped_frame);
  // do stuff with tensor
}

That can be called from a button such as below

<video id="cam" autoplay muted></video>
<button onclick="predict_img()">
  predict current frame
</button>

Is there a way to smooth the graph in MUI lineplot?

enter image description here
I am searching for a method to smoothen the graphs that are in this Image. I tried several methods but couldn’t find a way to make the graphs smoother or better aesthetically. I don’t mind slightly changing the data point values to achieve this. I am preferably searching for any inbuilt algorithms in the MUI line plot, any algorithm that smoothens the data coordinated itself would also be fine.

This is the graph code I am using:

import * as React from 'react';
import Paper from '@mui/material/Paper';
import Box from '@mui/material/Box';
import Checkbox from '@mui/material/Checkbox';
import FormControlLabel from '@mui/material/FormControlLabel';
import { ChartContainer } from '@mui/x-charts/ChartContainer';
import { ResponsiveChartContainer } from '@mui/x-charts/ResponsiveChartContainer';
import { BarPlot } from '@mui/x-charts/BarChart';
import { LinePlot, MarkPlot } from '@mui/x-charts/LineChart';
import { ChartsXAxis } from '@mui/x-charts/ChartsXAxis';
import { ChartsYAxis } from '@mui/x-charts/ChartsYAxis';
import { ScatterPlot, ChartsLegend  } from '@mui/x-charts';


function createSmoothCurve(x, y) {
  // Assuming x and y are arrays of the same length
  if (x.length !== y.length) {
    throw new Error('The length of x and y arrays must be the same');
  }

  // Sort the points by the x-axis
  let points = x.map((xi, i) => ({ x: xi, y: y[i] }));
  // points.sort((a, b) => a.x - b.x);

  let xlst = [];
  let ylst = [];

  // The number of intermediate points you want to create between each pair of points
  let granularity = 10;

  let curvePoints = [];

  for (let i = 0; i < points.length - 1; i++) {
    let start = points[i];
    let end = points[i + 1];

    for (let j = 0; j <= granularity; j++) {
      let t = j / granularity;
      let xt = (1 - t) * start.x + t * end.x;
      let yt = (1 - t) * start.y + t * end.y;
      curvePoints.push({ x: xt, y: yt });
      xlst.push(xt)
      ylst.push(yt)
    }
  }

  // Add the last point
  curvePoints.push(points[points.length - 1]);



  return [xlst,ylst];
}


export default function GraphComponent(props) {
  const [isResponsive, setIsResponsive] = React.useState(false);

  let {Time, LinePoints, YaxisLabel, ScatterPoints} = props;
  
  const Container = isResponsive ? ResponsiveChartContainer : ChartContainer;
  const sizingProps = { width: 700, height: 300 };

  const [smoothX, smoothY] = createSmoothCurve(LinePoints, Time);


  return (
    <Box sx={{ width: '100%'}}>
      <Paper sx={{ width: 700, height: 300, overflow: 'hidden' }} elevation={3}>
        {/* @ts-ignore */}
        <Container
          sx={{pr:2}}
          series={[
            {
                type: 'scatter',
                data: ScatterPoints,
                label: 'test2'
              },
            {
              // line: "curve",
              type: 'line',
              data: LinePoints,
              label: 'test1',
              // tension: 0.1
            },
          ]}
          // yAxis={[{ label: 'MPs concentration in spleen (mg/kg)', id: 'y-axis-id'}]}
          yAxis={[{ id: 'y-axis-id'}]}
          xAxis={[
            {
              data: Time,
              // scaleType: 'curve',
              id: 'x-axis-id',
            },
          ]}
          width={700}
          height={300}
          grid={{ vertical: true, horizontal: true }}
        >
          <ScatterPlot />
          <LinePlot />
          {/* <MarkPlot /> */}
          <ChartsXAxis label="Time" position="bottom" axisId="x-axis-id" />
          <ChartsYAxis label="MPs concentration in spleen (mg/kg)" position="right" axisId="y-axis-id" labelStyle={{fontSize:15, transform:'translateX(-770px) translateY(180px) rotate(-90deg)'}} tickLabelStyle={{fontSize:12, transform:'translateX(2px)'}}/>
          <ChartsLegend />
          
        </Container>
      </Paper>

      
    </Box>
  );
}

Creating reusable form components using Formik and Yup library for react + vite

I am trying to create a react+vite project where I am trying to implement a reusable form components using Formik and Yup but not able to achieve this yet.
I have created a component called <AppInputField/> which is just an <input/> field with custom css to suit my design of the overall website. Similar to this I have <AppButton/> which is again just <button/>. And all the required attributes I am passing through props. Now when I am trying to create a similar for <AppForm/> which will wrap around formik library I am having a hard time solving it. From the searches I have came to know that it is related useFormik() and useFormikContext() but again not 100% sure.
Here’s my codes :

SignUp.jsx

const SignUp = () => {
  
const signUpSchema = Yup.object({
  name: Yup.string().min(2).max(25).required("Please enter your name"),
  });

  return (
    <>
    <AppForm
        initialValues={{
            name : ''
        }}
        validationSchema={signUpSchema}
        onSubmit={(values) => {console.log("Submitted with these valuesn" + values)}}
    >
        <AppInputField 
          name='name'
          label='Enter your name'
          placeholder='XYZ'
        />
        <SubmitButton title='Register'/>
    </AppForm>
    </>
  );
};

export default SignUp;

AppForm.js

function AppForm({initialValues, onSubmit, validationSchema, children}) {
    return (
        <Formik
            initialValues={ initialValues }
            onSubmit={ onSubmit }
            validationSchema={ validationSchema } 
        >
                {children}
                {/* children passed as props here are the inner components of form 
meaning AppInputField and SubmitButton
this actually renders the inside components */}
        </Formik>
    );
}
export default AppForm;

AppInputField.jsx

const AppInputField = ({name, label, placeholder, type='text') => {
    const { handleChange, handleBlur, values } = useFormikContext();
    return (
        <>
        <label htmlFor={name} className="input-label">{label}</label>
        <input
            autoComplete="off"
            className="input-text"
            id={name}
            name={name} 
            onChange={handleChange}
            onBlur={handleBlur}
            placeholder={placeholder}
            type={type}
            value={values[name]}
        />
        </>
    )
}
export default AppInputField

SubmitButton.jsx

function SubmitButton({title}) {
    const { handleSubmit } = useFormikContext();
    return (
        <AppButton 
            title={title} 
            type='submit' 
            onClick={handleSubmit}
        />
    );
}
export default SubmitButton;

So the error when clicking on SubmitButton is
Uncaught TypeError: Cannot destructure property 'handleSubmit ' of 'useFormikContext(...)' as it is undefined.
If I change it to something submitForm then same error. Also when using the useFormik() the code of the components is changed but there also no success. When using useFormik I cannot use the context in another component. I need to use all in the same form at the same jsx file. Hope i am able to explain my objective. This kind of abstraction I had came across when going through course of react-native of Mosh Hemdani. And I found it so beautiful that I want to achieve this in my react+vite project. Any help would be appreciated.

Unable to validate string with regex stored in an object – Jquery [duplicate]

I have a javascript object that is initialized when the app loads. It contains all of my regex strings (sample below). I want to validate the inputs of a form using this regex string and javascript .test method but can only get it to return false. What am I missing?

sdregex shown from console.log: {"charint":"/^[a-zA-Z0-9_]+$/","intstr":"/^\d$/","uuid":"/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/","keyname":"/^[a-z0-9]+(\-[a-z0-9]+){0,1}$/","keyname_list":"/^([a-z0-9]+(\-[a-z0-9]+){0,1}){1}(,([a-z0-9]+(\-[a-z0-9]+){0,1}))*$/","year":"/^\d{4}$/"}


function validate(){
    var re = new RegExp(sdregex.charint);
    
    if(re.test($('#inputid').val())){
        alert("yes");
    }else{
        alert("no");
    }
}

SPA express routing but allowing NPM Package imports

I tried to create a single page application which serves index.html from an express router. My express router looks like this:

const express = require('express');
const path = require('path');
const fs = require("fs")

const app = express();

const indexPath = path.join(__dirname, 'index.html')


app.get('*', (req, res) => {
  const urlPath = path.join(__dirname, req.path)
  if(req.path === "/"){
    res.sendFile(indexPath)
  } else{
    fs.access(urlPath, fs.constants.F_OK, (err) => {
      if(err){
        res.sendFile(indexPath)
      } else{
        res.sendFile(urlPath);
      }
    })
  }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running at http://127.0.0.1:${PORT}`);
});

I tried to prevent using a static folder, but also tried it with one and still have the same problem.
My problem is the following: This express router serves the html file on every route, except when a file is requested, for example in a import like import { func } from "file.js". The problem is that I know can’t import npm packages, because it’ll try to affiliate them with files. import { v4 } from "uuid" gives the following error:

Uncaught TypeError: Failed to resolve module specifier "uuid". Relative references must start with either "/", "./", or "../".

I tried different methods for routing and modifying the server file but I didn’t get anywhere, that’s why I’m asking here. The goal is to have a server that serves index.html for every route and handling the routing in the client. I also need to be able to import and export files inside the module in my client and additionally to files I want to be able to use npm packages.

I’d be really glad if someone could help. Thank you.

Extracting elements of a array

I want to extract elements of a array, then store them in a new array and compare them to another array. The problem ist, that I don’t want to extract elements in a order.
I used the .slice function for extracting elements in a order.

let winArray = [playerSymbol, playerSymbol, playerSymbol]
if (playingFielddArray.slice(0, 3).every(v => winArray.includes(v))) {
    // Do something }

This is working fine. This would be my try for elements that are not in order:

    let newArray = [playingFielddArray[0], playingFielddArray[4], playingFielddArray[8]]
    if(newArray.every(v => winArray.includes(v))){ // Do something }

But I don’t like this solution. I would need to create many arrays and compare them.

Is there a function I can use for that?