How to insert a css class via java script?

I have a particular code and I would need to add a css class only to this code, but via javascript.

Example:

<div class="info-list-item">
<div class="info-label">A:</div>
<div class="info-val">abcd</div>
</div>
<div class="info-list-item">
<div class="info-label">C:</div>
<div class="info-val">cccc</div>
</div>
<div class="info-list-item">
<div class="info-label">B:</div>
<div class="info-val">dcba</div>
</div>

How can I insert an additional class called EXTRA only for a and b via java script?

Example:

<div class="info-list-item">
<div class="info-label" class="extra">A:</div>
<div class="info-val" class="extra">abcd</div>
</div>
<div class="info-list-item">
<div class="info-label">C:</div>
<div class="info-val">cccc</div>
</div>
<div class="info-list-item">
<div class="info-label" class="extra">B:</div>
<div class="info-val" class="extra">dcba</div>
</div>

Thanks for the help.

Cannot set a custom filename to a document when saving it as PDF using ReactToPrint

I’m using the react-to-print library for printing a document.
Basically when I click a button the following function is called for managing the printing:

const handlePrint = useReactToPrint({
    documentTitle: subject,  // I want the downloaded file to have subject variable value as filename
    content: () => componentRef.current,
    onAfterPrint: () => setIsPrinting(false)
});

On localhost everything works fine, but in production, the React application is embedded in an iframe.
This seems to cause a problem with the name of the document that is downloaded.

Instead of what is specified in documentTitle attribute the filename is the same as the page title of the page that embeds my react app.

Is there a way to set a custom name to the downloaded file even if the printed element is inside an app embedded in an iframe?

How to setup a mockEnvironment in @telegram-apps/sdk version 3?

Environment: Vanilla TS + Vite

Package: @telegram-apps/sdk – v3.4.0

I have used a bunch of different ways to try and use mockEnvironment but it just doesn’t seem to work, and there’s no documentations for the new version about the mock that I could find, I’m not sure how to make this work.

A couple of things I’ve tried that didn’t work:

mockTelegramEnv({
  tgWebAppThemeParams: {
    accent_text_color: '#6ab2f2',
    bg_color: '#17212b',
    button_Color: '#5288c1',
    button_text_color: '#ffffff',
    destructive_text_color: '#ec3942',
    header_bg_color: '#17212b',
    hint_color: '#708499',
    link_color: '#6ab3f3',
    secondary_bg_color: '#232e3c',
    section_bg_color: '#17212b',
    section_header_text_color: '#6ab3f3',
    subtitle_text_color: '#708499',
    text_color: '#f5f5f5',
  },
  tgWebAppData: {
    user: {
      id: 99281932,
      first_name: 'Andrew',
      last_name: 'Rogue',
      username: 'rogue',
      language_code: 'en',
    },
    hash: '89d6079ad6762351f38c6dbbc41bb53048019256a9443988af7a48bcad16ba31',
    auth_date: new Date(1716922846000),
    signature: 'abc',
    start_param: 'debug',
    chat_type: 'sender',
    chat_instance: '8428209589180549439',

  },
  tgWebAppVersion: "8.0",
  tgWebAppPlatform: "tdesktop",
  tgWebAppStartParam: "debug"
});

and:

    window.Telegram = {
      tgWebAppThemeParams: {
        accent_text_color: '#6ab2f2',
        bg_color: '#17212b',
        button_Color: '#5288c1',
        button_text_color: '#ffffff',
        destructive_text_color: '#ec3942',
        header_bg_color: '#17212b',
        hint_color: '#708499',
        link_color: '#6ab3f3',
        secondary_bg_color: '#232e3c',
        section_bg_color: '#17212b',
        section_header_text_color: '#6ab3f3',
        subtitle_text_color: '#708499',
        text_color: '#f5f5f5',
      },
      tgWebAppData: {
        user: {
          id: 99281932,
          first_name: 'Andrew',
          last_name: 'Rogue',
          username: 'rogue',
          language_code: 'en',
        },
        hash: '89d6079ad6762351f38c6dbbc41bb53048019256a9443988af7a48bcad16ba31',
        auth_date: new Date(1716922846000),
        signature: 'abc',
        start_param: 'debug',
        chat_type: 'sender',
        chat_instance: '8428209589180549439',

      },
      tgWebAppVersion: "6.0",
      tgWebAppPlatform: "web",
      tgWebAppStartParam: "debug"
    } as LaunchParams;

How To Replace Google Maps Marker Icon With My Own?

I have set an custom icon within the Google Maps API using Javascript, and jQuery.
I am trying to replace the Google Maps Marker Icon with my own but it keeps replacing the icon with the default Google Maps API icon. Is this a Bug or is their a way to fix this issue ?

<!DOCTYPE html>
<html>
<head>
  <title>Map Route with Custom Markers</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg"></script>
  <style>
    #map {
      height: 400px;
      width: 100%;
    }
  </style>
</head>
<body>
  <div id="map"></div>

  <script>
    $(document).ready(function() {
      var map;
      var directionsService;
      var directionsRenderer;

      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: 40.7128, lng: -74.0060}, // New York
          zoom: 10
        });

        directionsService = new google.maps.DirectionsService();
        directionsRenderer = new google.maps.DirectionsRenderer({
          map: map
        });
      }

      function calculateAndDisplayRoute(start, end, waypoints) {
        directionsService.route({
          origin: start,
          destination: end,
          waypoints: waypoints,
          optimizeWaypoints: true,
          travelMode: 'DRIVING'
        }, function(response, status) {
          if (status === 'OK') {
            directionsRenderer.setDirections(response);

            var route = response.routes[0];
            for (var i = 0; i < route.legs.length; i++) {
              addCustomMarkers(route.legs[i].start_location, 'Start');
              addCustomMarkers(route.legs[i].end_location, 'End');
            }

            if (waypoints) {
               waypoints.forEach(function(waypoint) {
                  addCustomMarkers(waypoint.location, 'Waypoint');
               });
            }
          } else {
            window.alert('Directions request failed due to ' + status);
          }
        });
      }
      
      function addCustomMarkers(location, label) {
          new google.maps.Marker({
            position: location,
            map: map,
            label: label,
            icon: { // Custom marker icon
              url: "https://i.postimg.cc/hvp0CVp9/detox-logo-1.png", // Replace with your icon URL
              scaledSize: new google.maps.Size(30, 30),
              labelOrigin: new google.maps.Point(15, -10)
            }
          });
      }

      initMap();

      // Example usage:
      var start = 'New York, NY';
      var end = 'Philadelphia, PA';
      var waypoints = [
        {
          location: "Trenton, NJ",
          stopover: true
        }
      ];
      calculateAndDisplayRoute(start, end, waypoints);
    });
  </script>
</body>
</html>

Example: https://jsfiddle.net/p6m3sk78/

I am expecting it to completely replace the default Google Maps icon.

Google Apps Script alert showing twice when called from HTML dialog

I’ve got three files that does one simple thing:

  1. User via custom menu opens a modal dialog
  2. User clicks button on modal dialog
  3. button click calls a function that displays a simple alert

That’s it. But…the alert gets displayed TWICE. Here is the code:

custom-menu.gs

function onOpen() {
  SpreadsheetApp.getUi().createMenu('custom menu')
      .addItem('button 1','someFunction')
      .addToUi();
}

gas-file.gs

function someFunction() {
  const htmlOutput = HtmlService.createHtmlOutputFromFile("html-file");
  SpreadsheetApp.getUi().showModalDialog(htmlOutput, "Some Title");
}

function someFunc1() {
  SpreadsheetApp.getUi().alert("someFunc1() has been called.")
}

html-file.html

<!DOCTYPE html>
<html>
  <body>
    <button type="button" onclick="submit()">Submit</button>
    <script>

      function submit() {
        google.script.run.someFunc1();
      }      

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

I’m completely baffled. Any help would be greatly appreciated. Thank you in advance!

Performance problem with the FileSystemWritableFileStream.write method

Context

One feature of my web application is copying file from A to B on user’s machine, not in the OPFS. The destination (B) is a mounted NFS, so the write speed is the Internet upload speed.

File size varies between 1 GB and 200 GB.

Here is my code to copy a file:

// Source file
const file = await fileHandle.getFile();

// Destination
const fileDestination = await location.getFileHandle(file.name, { create: true });

const writable = await fileDestination.createWritable();
try {
  await writable.write(file);
  await writable.close();
}
catch (e) {
  console.error(e);
}

Problem

I notice that, the copy speed of the code above is much slower than manual copy with Ctrl + C and Ctrl + V. It fluctuates between 2 to 10 times slower.

The FileSystemWritableFileStream.write() documentation says:

No changes are written to the actual file on disk until the stream has been closed. Changes are typically written to a temporary file instead.

Does it mean that when I use the write() method, it first writes to a temporary file. And when I close the stream, the temporary file is moved to the actual file destination?

If so,

  1. Where does this temporary file locate?
  2. How can I avoid this? Can I write directly to the destination file instead?

I notice that I can also do

await file.stream().pipeTo(writable);

instead of using the FileSystemWritableFileStream.write() method. But I’m not sure if it helps.

Looping over a map without using get or set methods [duplicate]

The question is about the 2342. Max Sum of a Pair With Equal Sum of Digits problem on leetcode.

I tried to use the map for my solution (here following my code):

const s = function(el){
    return (''+el).split('').reduce((acc, el) => acc+parseInt(el), 0);
}
var maximumSum = function(nums) {
   let m = new Map();
   let max = 0;
   nums.map(el =>{
    if(!m[s(el)]){
        m[s(el)] = [el, 1];
    }else{
        m[s(el)][0]+=el;
        m[s(el)][1]++;
    }
   });
   for(let el of m.values())
    console.log(el);
};

The parameter nums is an array (if you want to try, it’s [18,43,36,13,7]). The map works correctly, in fact when I do console.log(m), it shows the map as expected. The problem is with the for…of loop, which does not work (I get no output or undefined). I read on other questions that it’s because you need to use the set() method, and that’s true, but I couldn’t create the correct map with that (because I don’t know how to then increase the elements).

Any suggestions on how I can iterate over the map without using the set method?
Thanks a lot!

How to mock GridFSBucket’s openUploadStream in Jest for image upload testing?

I’m fairly new to the Jest testing framework and am writing unit tests for a user registration endpoint that handles image uploads using GridFS. I’m getting the following error when running my tests:

Failed to upload image: Cannot read properties of undefined (reading ‘openUploadStream’)

RegisterUser.test.mjs file

import { RegisterUser } from "../../controllers/RegisterUser.mjs";
import { jest } from '@jest/globals'

// jest.mock('mongoose', () => ({
//     once: jest.fn((event, callback) => {
//         if (event === 'open') {
//             callback();
//         }
//     }),

//     db: {}
// }));

// jest.mock('mongodb', () => ({
//     GridFSBucket: jest.fn().mockImplementation(() => ({
//         openUploadStream: jest.fn().mockReturnValue({
//             id: 'mockFileId',
//             on: jest.fn((event, callback) => {
//                 if (event === 'finish') {
//                     callback();
//                 } else if (event === 'error') {
//                     callback(new Error("Mocked error"));
//                 }
//             }),
//         })
//     }))
// }));

// jest.mock('stream', () => ({
//     Readable: jest.fn(() => ({
//         push: jest.fn(),
//     }))
// }));

const mockUploadImage = jest.fn();

// Mock the entire module with the tracked function
jest.mock('../../config/gridfs-setup.mjs', () => ({
    uploadImage: mockUploadImage,
    gfs: {
        openUploadStream: jest.fn()
    }
}));

describe('Profile Image Upload', () => {
    it("should handle image upload and save it to the database", async () => {
        let mockRequest = {
            body: {
                email: "[email protected]",
                password: "Password?123",
                username: 'testuser',
                mobileNumber: "+6582183334",
                image: 'data:image/png;base64,abc123',
            }

        }

        let mockResponse = {
            status: jest.fn().mockReturnThis(),
            json: jest.fn()
        };

        const base64Image = mockRequest.body.image;
        const username = mockRequest.body.username;

        const imageBuffer = Buffer.from(base64Image.replace(/^data:image/w+;base64,/, ''), 'base64');

        jest.spyOn(Date, 'now').mockImplementation(() => new Date('2025-01-01'));
        const imageName = `profile-${Date.now()} - ${username}`;

        await RegisterUser(mockRequest, mockResponse);

        expect(mockUploadImage).toHaveBeenCalled();
    })
})

gridfs-setup.mjs file

import mongoose from "mongoose";
import { GridFSBucket } from 'mongodb';
import { Readable } from 'stream';

const connection = mongoose.connection;
let gfs;

connection.once('open', () => {
    gfs = new GridFSBucket(connection.db, {
        bucketName: "images" // Creating a special database for images
    });
});

const uploadImage = async (imageName, imageBuffer, metadata = {}) => {
    try {
        // Creates a writable stream that we can use to write our image data into GridFS
        const uploadStream = gfs.openUploadStream(imageName, {
            metadata: {
                ...metadata,
                uploadDate: new Date()
            }
        });

        // Create a readable stream for us to read the data and connect it with uploadStream (writable)
        const bufferStream = new Readable();
        bufferStream.push(imageBuffer);
        bufferStream.push(null); // Signals we are are done sending the data

        // When everything is safely stored, we return the storage location or the error
        return new Promise((resolve, reject) => {
            bufferStream.pipe(uploadStream) // Connects the bufferStream(readable) to the uploadStream(writable)
                .on('finish', () => resolve(uploadStream.id))
                .on('error', reject);
        });
    } catch (error) {
        throw new Error(`Failed to upload image: ${error.message}`);
    }
};

export { gfs, uploadImage };

RegisterUser.mjs file (controller)

import User from "../models/User.mjs";
import OTP from "../models/OTPSchema.mjs";
import bcrypt from "bcrypt";
import { uploadImage } from "../config/gridfs-setup.mjs";
import sendEmail from "./SendOTP.mjs";


export const RegisterUser = async (req, res) => {
    // try {
    const { email, password, username, mobileNumber, image, googleId } = req.body;
    // Submitted image data comes as a base64 string and we need to convert it to binary data
    // for computers to handle. 
    const imageBuffer = Buffer.from(
        image.replace(/^data:image/w+;base64,/, ''),
        'base64'
    );

    // Create a unique name for the image file 
    const imageName = `profile-${Date.now()} - ${username}`

    // Send the image to GridFS storage system and get back an id
    const fileId = await uploadImage(imageName, imageBuffer, {
        type: 'profile',
        username: username
    });
    // const newUser = new User({
    //     googleId,
    //     email,
    //     password,
    //     username,
    //     mobileNumber,
    //     profileImage: fileId,
    //     authProvider: 'local',
    // });

    // req.session.pendingUser = newUser;

    // const otp = Math.floor(1000 + Math.random() * 9000).toString();
    // await OTP.create({
    //     email,
    //     otp: await bcrypt.hash(otp, 10)
    // });

    // const subject = "Registration Email Verification";
    // const message = `Please use the following One Time Password: ${otp}. This OTP will expire in 5minutes.`

    // try {
    //     await sendEmail({
    //         recipient: email,
    //         subject: subject,
    //         message: message
    //     });

    // } catch (error) {
    //     console.error('Email sending failed:', error);
    // }

    res.status(201).json({
        success: true,
        redirectTo: `/authentication/verify/${newUser._id}`,
    });

    // } catch (error) {
    //     if (error.code === 11000) {
    //         // The key is essential for attaching the error message to the corresponding 
    //         // error object in the react hook form (client)
    //         const keys = Object.keys(error.keyPattern);
    //         const key = keys[0];
    //         if (error.keyValue.email) {
    //             return res.status(400).json({
    //                 success: false,
    //                 message: "Email address is already in use",
    //                 key: key,
    //             })
    //         } else if (error.keyValue.username) {
    //             return res.status(400).json({
    //                 success: false,
    //                 message: "Username is taken",
    //                 key: key,
    //             })
    //         } else if (error.keyValue.mobileNumber) {
    //             return res.status(400).json({
    //                 success: false,
    //                 message: "Mobile number is already in use",
    //                 key: key,
    //             })
    //         }
    //     }

    //     res.status(500).json({
    //         success: false,
    //         message: "There is something wrong with the server. Please try again later."
    //     })
    // }
}

I have attempted to mock both the Mongoose and MongoDB modules, but I’m still encountering the same error.

side bar slideOut animation doesn’t execute at all

I am implementing my own React SideBar component. I am able to make it slide in and unable to make it slide out. fade-out executed but slide-out didn’t. I really have no idea why. Please help! Thanks in advance.

This is the simplified tsx code:

import React, {useState} from 'react';
import './AccountSideBar.css';
import LoginUtils from '../utils/LoginUtils';
import {IMAGE_PATH} from "../utils/BrowserConfig";

interface AccountSideBarProps {
    onClose: () => void;
    onLogout: () => void;
}

const AccountSideBar: React.FC<AccountSideBarProps> = ({ onClose, onLogout }) => {
    const [isClosing, setIsClosing] = useState(false);

    const handleClose = () => {
        setIsClosing(true);
        setTimeout(onClose, 300);
    };

    return (
        <div className={`sidebar-overlay ${isClosing ? 'fade-out' : ''}`} onClick={handleClose}>
            <div className={`account-sidebar ${isClosing ? 'slide-out' : ''}`} onClick={(e) => e.stopPropagation()}>
                <div>
                    <button className="close-button" onClick={handleClose}>×</button>
                </div>
            </div>
        </div>
    )
        ;
};

export default AccountSideBar;

This is the css

.sidebar-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  justify-content: flex-end;
  animation: fadeIn 0.3s ease-in-out;
}

.fade-out {
  animation: fadeOut 0.3s forwards;
}

.slide-out {
  animation: slideOut 0.3s forwards;
}

@keyframes fadeIn {
  from {
    background-color: rgba(0, 0, 0, 0);
  }
  to {
    background-color: rgba(0, 0, 0, 0.5);
  }
}

@keyframes fadeOut {
  from {
    background-color: rgba(0, 0, 0, 0.5);
  }
  to {
    background-color: rgba(0, 0, 0, 0);
  }
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
  }
  to {
    transform: translateX(0);
  }
}

@keyframes slideOut {
  from {
    transform: translateX(0);
  }
  to {
    transform: translateX(100%);
  }
}
.account-sidebar {
    width: 300px;
    height: 100%;
    color: #fff;
    box-shadow: -2px 0 5px rgba(0, 0, 0, 0.5);
    display: flex;
    flex-direction: column;
    padding: 20px;
    animation: slideIn 0.3s ease-in-out;
}

.account-sidebar .close-button {
    position: absolute;
    top: 10px;
    right: 10px;
    background: none;
    border: none;
    color: #fff;
    font-size: 36px;
    cursor: pointer;
}

Pixels[] in p5.js doesn’t return proper color values upon canvas resize

I’m working on a generative art project and seem to be running into an issue with the pixels function. Part of the artwork algorithm involves drawing circles (i.e., trees) in certain parts of the canvas where only the background color is showing. I’m using the pixels array to compare colors of the pixels in the canvas to a background color to do this. The issue I’m having is that when I resize the canvas and it subsequently re-draws, some of the circles disappear while others randomly appear. This even happens in areas of the canvas where it’s absolutely clear that the background color exists. From my investigation so far, it appears that the pixels array isn’t returning colors for some pixels that directly match the background color, even when they clearly should.

The code for this particular function is provided below. Note that I verified that the probability part of the algorithm is not the culprit here. I’m also seeding the random function with a consistent value, so everything should be the same when it re-draws after resizing. The problem has to do with the color checking. Any ideas?

// Function to draw random trees in areas where the background color exists and 
// when a point exists within a certain probability distribution of a line or 
// set of lines
// bg: background color
// treeColor: the color of trees to be drawn on the canvas
function drawTrees(bg,treeColor) {
  
  fill(treeColor);
  noStroke( );
  
  // Generate an array of lines that will be used to determine where to plot the tree distributions
  let numClusters = 0;
  if (trees > 0) {
    numClusters = Math.floor(random(3,8));
  }
  let lines = new ArrayList();
  for (let l = 0; l < numClusters; l++) {
    let p0x = random(0, 1) * canvasMin;
    let p0y = random(0, 1) * canvasMin;
    let p1x = random(0, 1) * canvasMin;
    let p1y = random(0, 1) * canvasMin;
    let p0 = new Point(p0x, p0y);
    let p1 = new Point(p1x, p1y);
    lines.add(new Line(p0,p1));
  }
  
  // Iterate through all pixels, per treeSpacing value
  loadPixels();
  for (let i = 0; i < 10000; i += 1) {
  
    // Set a random point
    let xPixP = random(0, 1) * canvasMin;
    let yPixP = random(0, 1) * canvasMin;
    let xPix = Math.round(xPixP);
    let yPix = Math.round(yPixP);
    
    // Check if the pixels around the point are only the background color
    let clear = true;
    let d = pixelDensity();
    let clearance = Math.floor(canvasMin/200);
    for (let j = -clearance; j < clearance; j++) {
        for (let k = -clearance; k < clearance; k++) {
            let index = 4 * d * ((yPix + j) * d * canvasMin + xPix + k);
            let cR1 = pixels[index];
            let cG1 = pixels[index + 1];
            let cB1 = pixels[index + 2];
            let cA1 = pixels[index + 3];
            let cR2 = red(bg);
            let cG2 = green(bg);
            let cB2 = blue(bg);
            let cA2 = alpha(bg);
            if (cR1 != cR2 || cG1 != cG2 || cB1 != cB2) {
                clear = false;
            }
        }
    }
  
    // Check closeness to each line
    let maxDist = canvasMin / random(4, 40);
    let prob = 0;
    for (let l = 0; l < lines.size(); l++) {
        let distFromL = getDistanceFromLine(lines.get(l), new Point(xPixP,yPixP));
        if (distFromL < maxDist) {
            prob = min(prob + (1 - (distFromL / maxDist)), 0.7);
        }
    }
  
    // Draw the tree if the probability is within a certain range and the pixels
    // around the point are only colored with the background color
    let randomCheck = random(0,1);
    if (clear && randomCheck < prob) {
    
        // Draw the trunk
        let trunkSize = canvasMin/200;
        circle(xPix,yPix,trunkSize);
    
        // Draw the bunches of leaves
        for (let i = 0; i < Math.floor(random(4,7)); i++) {
            circle(xPix + random(-trunkSize/2,trunkSize/2),yPix + random(-trunkSize/2,trunkSize/2), random(trunkSize,trunkSize*2));
        }
    }
  }
}

JSCAD rendering objects

I am making an application that create objects according to the code given by user. I use JSCAD(OpenJscad) but I couldnt get render I get some errors this is the last error I had:
index.html?_ijt=eccib74kso9ucbd5sgsm6ojbs3:42 Uncaught TypeError: window.jscadRenderer.createRenderer is not a function
at window.renderJSCAD (index.html?_ijt=eccib74kso9ucbd5sgsm6ojbs3:42:47)
at HTMLButtonElement.onclick (index.html?_ijt=eccib74kso9ucbd5sgsm6ojbs3:20:33)

I am not experienced at jscad so I couldn’t figured out why the app throws this error.

My code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JSCAD Web App</title>
    <script language="javascript" src="https://unpkg.com/@jscad/modeling" id="MODELING"></script>
    <script language="javascript" src="https://unpkg.com/@jscad/regl-renderer"></script>
    <script>
        document.addEventListener("DOMContentLoaded", () => {
            window.jscad = globalThis.jscadModeling;
            window.jscadRenderer = globalThis.jscadReglRenderer;
        });
    </script>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>JSCAD Web App</h1>
<textarea id="editor">function main() { return jscad.primitives.cube({size: 10}); }</textarea>
<button onclick="renderJSCAD()">Render Model</button>
<div id="renderArea"></div>

<script>
    window.renderJSCAD = function() {
        if (!window.jscad || !window.jscadRenderer) {
            console.error("JSCAD veya Renderer kütüphanesi yüklenmedi.");
            return;
        }

        const { primitives } = window.jscad;
        const { cube } = primitives;
        const script = document.getElementById('editor').value;
        const design = new Function('return ' + script)();

        document.getElementById('renderArea').innerHTML = '';
        let viewerCanvas = document.createElement('canvas');
        viewerCanvas.width = 600;
        viewerCanvas.height = 400;
        document.getElementById('renderArea').appendChild(viewerCanvas);

        // Correct renderer initialization
        const renderer = window.jscadRenderer.createRenderer({ glOptions: { canvas: viewerCanvas } });

        // Draw the solids
        renderer.draw({ solids: [design] });
    }
</script>
</body>
</html>

I asked questions about this error to ChatGPT but it tries this createRenderer method. I think createRenderer is older function of jscad.

Flask Route and JS Script Are Not Working

I have a Flask app that calls an alert using JS in a route. The alert never pops up when I go to the route from the home page. The only time it works is when it is rendered from the get go (localhost:5000/register) or refreshed by the browser (/register). Why wont the alert work from the Flask home route when clicked. It seems simple enough. Here is the set up:

app.py:

from app import create_app
app = create_app()
if __name__ == "__main__":
    app.run(debug=True)

routes.py:

    from Flask import Blueprint
    routes_bp = Blueprint('routes', __name__, url_prefix="/")
    
    @routes_bp.route('/')
        def home():
        return render_template('home.html')

    @routes_bp.route('/register')
    def register():
        return render_template('register.html')

init.py:

from flask import Flask
from app.routes import routes_bp 

def create_app():
    app = Flask(__name__ )
    app.register_blueprint(routes_bp)
    return app

base.html:

<html>
<body>
<div>
{% block body %}{% endblock %}
</div>

<script src="{{ url_for('static', filename='js/client.js') }}" defer></script>
// above works when load page first time , using refresh button on browser
</body>
</html>

home.html:

{% extends "base.html" %}

{% block body %}
<a href="{{ url_for('routes.register') }}"> Register</a>
<a href="{{ url_for('routes.login') }}"> Login</a>
{% endblock %}

register.html:

{% extends "base.html" %}

{% block body %}
html here ...
<script type="text/javascript"> alert('hello')</script> 
// alert does not work when I click route from home.html, does work when I refresh URL from browser 
{% endblock %}

Changing inline CSS using JavaScript isn’t working

I’m trying to change the width of an element using JavaScript.

This doesn’t throw any error. It instead silently ignores the code.

pageSettings = {
  'padding': 16    
}
document.querySelector('#container').style.setProperty(
  'width',
  `calc(100vw - (20em + ${pageSettings['padding'] * 2}px)) !important;`
)
<div class='container' id='container'>
  <p>Content</p>
</div>

Two value arguments in the forEach method in JavaScript [closed]

I have a question about the forEach method in Javascript and the arguments that it receives. I want to know if it is possible to add two VALUE arguments into the forEach function.

My sorted function is not working because (I think!) it is in the 3rd placeholder and js is expecting an array (I might be wrong). Therefore sort keeps defaulting to true when it should be false. Does anyone have any solutions to fix this?

  combinedObj.forEach(function ({ movs, date = obj }, i, sort = false) {
    if (sort) {
      combinedObj.sort(function (a, b) {
        return a.movs - b.movs;
      });
    } else {
      return combinedObj;
    }

Any reply appreciated. Thank you.