JavaScript returning NaN when page is served from web server [closed]

The following Javascript gets an the coordinates from an image map, recalculates the coordinates based on the rendered size of the image and displays a modal based on the area of the image being hovered over. This works fine when using chrome on my local machine, but when the page is loaded from the web server, the new coordinates for the rendered image are returned as NaN. Anybody got any thoughts on why this is going wrong and what I can do to fix it?

<script>
        // Get the image element and the map areas
        var image = document.getElementById("team-image");
        var areas = document.querySelectorAll('map[name="team-map"] area');

        // Get the original image size
        var originalImageWidth = image.naturalWidth;
        var originalImageHeight = image.naturalHeight;

        // Calculate the actual pixel coordinates based on the original and displayed image sizes
        function calculatePixelCoordinates(coords, image) {
            var imageWidth = image.offsetWidth;
            var imageHeight = image.offsetHeight;

            var coordArray = coords.split(",");
            var pixelCoords = [];

            for (var i = 0; i < coordArray.length; i++) {
                if (i % 2 === 0) {
                    pixelCoords.push((parseInt(coordArray[i])) / originalImageWidth * (imageWidth));
                } else {
                    pixelCoords.push((parseInt(coordArray[i])) / originalImageHeight * (imageHeight));
                }
            }

            return pixelCoords.join(",");
        }

        // Add event listeners to each map area
        areas.forEach(function (area) {
            area.addEventListener("mouseover", function () {
                var modalId = area.dataset.modal;
                var modal = document.getElementById(modalId);
                modal.style.display = "block";
            });

            area.addEventListener("mouseleave", function () {
                var modalId = area.dataset.modal;
                var modal = document.getElementById(modalId);
                modal.style.display = "none";
            });

            // Update the coordinates when the image is loaded or resized
            image.addEventListener("load", function () {
                var pixelCoords = calculatePixelCoordinates(area.getAttribute("coords"), this);
                area.setAttribute("coords", pixelCoords);
            });

            window.addEventListener("resize", function () {
                var pixelCoords = calculatePixelCoordinates(area.getAttribute("coords"), image);
                area.setAttribute("coords", pixelCoords);
            });
        });

        // Add event listeners to close the modals
        var closeButtons = document.getElementsByClassName("close");
        for (var i = 0; i < closeButtons.length; i++) {
            closeButtons[i].addEventListener("click", function () {
                var modal = this.parentElement;
                modal.style.display = "none";
            });
        }

    </script>

Just scratching my head here, I’m not that up to speed on Javascript

Edit:

The orignal image map is as follows:

                <map name="team-map">
                <area shape="rect" coords="0,0,166,400" alt="sally" data-modal="modal1">
                <area shape="rect" coords="166,0,322,400" alt="issy" data-modal="modal2">
                <area shape="rect" coords="322,0,450,400" alt="tracy" data-modal="modal3">
                <area shape="rect" coords="450,0,568,400" alt="sharon" data-modal="modal4">
                <area shape="rect" coords="568,0,695,400" alt="annalisa" data-modal="modal5">
                <area shape="rect" coords="695,0,900,400" alt="lynne" data-modal="modal6">
            </map>

These coordinates are based on the orginal size of the image (900×400)

This gets read in the “// Get the image element and the map areas” and the new coordinates are recalculated based on the rendered size of the image and returns a variable “pixelCoords”, which are then put into a string and returned to the browser.

On my local machine, the map is rendered as:

    <map name="team-map">
                <area shape="rect" coords="0,0,650.9066666666666,1570.4225352112676" alt="sally" data-modal="modal1">
                <area shape="rect" coords="650.9066666666666,0,1265.1822222222222,1570.4225352112676" alt="issy" data-modal="modal2">
                <area shape="rect" coords="1265.1822222222222,0,1772.3822222222223,1570.4225352112676" alt="tracy" data-modal="modal3">
                <area shape="rect" coords="1772.3822222222223,0,2235.9066666666668,1570.4225352112676" alt="sharon" data-modal="modal4">
                <area shape="rect" coords="2235.9066666666668,0,2736.062222222222,1570.4225352112676" alt="annalisa" data-modal="modal5">
                <area shape="rect" coords="2736.062222222222,0,3544.7644444444445,1570.4225352112676" alt="lynne" data-modal="modal6">
            </map>

Whereas the map when served by the server is rendered as:

    <map name="team-map">
                <area shape="rect" coords="NaN,NaN,NaN,NaN" alt="sally" data-modal="modal1">
                <area shape="rect" coords="NaN,NaN,NaN,NaN" alt="issy" data-modal="modal2">
                <area shape="rect" coords="NaN,NaN,NaN,NaN" alt="tracy" data-modal="modal3">
                <area shape="rect" coords="NaN,NaN,NaN,NaN" alt="sharon" data-modal="modal4">
                <area shape="rect" coords="NaN,NaN,NaN,NaN" alt="annalisa" data-modal="modal5">
                <area shape="rect" coords="NaN,NaN,NaN,NaN" alt="lynne" data-modal="modal6">
            </map>

How to find an element in JSX using useRef in React

In my webpage, there is a form that is loaded via an iframe.

I can access the iframe with a ref:

const formRef = useRef(null)

<FormIframe ref={formRef} />

The iframe will return a bunch of JSX, and inside there, I know that there is an element that has the id of “first_name”

<input id="first_name" />

How do I access that element using the ref so that I can do stuff with it? The following does NOT work:

const el = formRef?.current?.getElementById("first_name")

I also tried using document with getElementById in a useEffect but that also didn’t work. It returned null:

useEffect(() => {
  if (document) {
    const el = document.getElementById("first_name")
    console.log(el)
  }
}, [])

Any ideas?

How to insert a bracket between the specified alphabet (i.e. A, D, F, R) and the digit using regular expression?

How to insert a bracket between the specified alphabet (i.e. A, D, F, R) and the digit using regular expression?

input:

A1
F42
D3
R6

Expected output:

(A)1
(F)42
(D)3
(R)6

What I have tried:

let inputString="f42"
let expPattern=/[ADFR]d{1,3}/ig;
 console.log(inputString.replace(expPattern,"(`$0`)"));

It returns “$0” only.

How can I implement the replacement?

Control points transformation

I want to display control points (THREE.Vector3 with 0 z coordinate) on a canvas. These control points has values less than 1, and the canvas has a 200px height and 400px width. So because of this, I transform these points (multiply each with 100) before displaying on the canvas, and after changing its position I reverse the transformation by dividing it by 100. I reverse the transformation because the original positions come from an engine and I have to write it back.

Can someone explain me why this transformation doesn’t work?

const transformControlPointsForDisplay = (controlPoints: THREE.Vector3[]) => controlPoints.map(cp => new THREE.Vector3(
    cp.x * 100.0,
    cp.y * 100.0,
    cp.z * 100.0
));
const reverseTransformControlPoints = (controlPoints: THREE.Vector3[]) => controlPoints.map(cp => new THREE.Vector3(
    Number((cp.x * 1.0 / 100).toFixed(10)),
    Number((cp.y * 1.0 / 100).toFixed(10)),
    Number((cp.z * 1.0 / 100).toFixed(10)),
));

How do you apply a CSS to a function?

I was just wondering on how i’m able to apply a CSS exactly like the image below to a java generated one-page QR ticket. Attempting to tinker with the current CSS does not yield the results I expect.
desired output

Here’s the current code for the function

function openQRCodeWindow(registrationId) {
  var qrCodeImage = generatedQRCode._el.firstChild.toDataURL("image/png");
  var firstName = document.getElementById("first-name").value;
  var lastName = document.getElementById("last-name").value;
  var email = document.getElementById("email").value;
  var contactNumber = document.getElementById("contact-number").value;
  var seatNumber = document.getElementById("seat-number").textContent;

  var newWindow = window.open();
  newWindow.document.write('<style>');
  newWindow.document.write('body { display: flex; flex-direction: column; align-items: center; background-image: url("megapolis background.png"); background-size: cover; }');
  newWindow.document.write('.container { display: flex; justify-content: space-between; align-items: center; padding: 50px; border: 2px solid #ccc; border-radius: 10px; width: 400px; }');
  newWindow.document.write('.qr-container { margin-right: 20px; }');
  newWindow.document.write('.details-container { text-align: right; }');
  newWindow.document.write('.button-container { margin-top: 20px; text-align: center; }');
  newWindow.document.write('.button-container button { margin: 0 5px; }');
  newWindow.document.write('</style>');

  newWindow.document.write('<h2>QR Code</h2>'); // Place the QR code title here
  newWindow.document.write('<div class="container" id="form-container">');
  newWindow.document.write('<div class="qr-container">');
  newWindow.document.write('<img src="' + qrCodeImage + '">');
  newWindow.document.write('</div>');
  newWindow.document.write('<div class="details-container">');
  newWindow.document.write('<h3>Details</h3>');
  newWindow.document.write('<p>Registration ID: ' + registrationId + '</p>'); // Display the Firebase-generated ID
  newWindow.document.write('<p>First Name: ' + firstName + '</p>');
  newWindow.document.write('<p>Last Name: ' + lastName + '</p>');
  newWindow.document.write('<p>Email: ' + email + '</p>');
  newWindow.document.write('<p>Contact Number: ' + contactNumber + '</p>');
  newWindow.document.write('<p>' + seatNumber + '</p>');
  newWindow.document.write('</div>');
  newWindow.document.write('</div>');
  newWindow.document.write('<div class="button-container">');
  newWindow.document.write('<button id="save-image-btn">Save Image</button>');
  newWindow.document.write('<button id="email-btn">Email</button>');
  newWindow.document.write('</div>');
  newWindow.document.close();

I am not familiar with adding css to js functions, so I tried different in-line styles but it didn’t seem to work out as expected.

Easiest way to create letter mappings for stadium seating letter effect

I’m trying to make a site where the user inputs their name and it appears in way as shown in the image.
[image1]!(https://i.stack.imgur.com/Iyi5J.jpg)
I got this mapping from chatgpt and made few modifications but it’s not as good as the desired requirement !(https://i.stack.imgur.com/cbAIO.png)

This is what I have at the moment !(https://i.stack.imgur.com/swxnV.png)I made 4 copies of rows and columns to make them appear bigger (with more seats/pixel boxes within them) but that doesn’t give a smooth effect.

**I want to know the easiest way to get the mapping for letters with as many blocks/seats/boxes as in image1. **

(I tried this site: https://www.text-image.com/convert/ but it wasn’t helpful and I only found one other question like this (https://blender.stackexchange.com/questions/235201/stadium-seating-letters) but they are using blender)

It’s my first post so I can’t add images

Why isn’t my function being called on submit?

Trying to call validateAndConfirm function on submit of below form but nothing is happening – please help 🙁

HTML Form-

<div id='form' class='center text'>
            <form method='post' onsubmit='return validateAndConfirm()'>
                <label for="firstname">First Name:</label>
                <input type="text" name="firstname" id="firstname" placeholder='Your first name...' autocomplete='given-name' required>
                <br>
                <label for="lastname">Last Name:</label>
                <input type="text" id="lastname" name="lastname" placeholder='Your last name...' autocomplete='family-name' required>
                <br>
                <label for="email">Email Address:</label>
                <input type="email" id="email" name="email" placeholder="[email protected]..." autocomplete='off' required>
                <br>
                <label for="confemail">Confirm Email Address:</label>
                <input type="email" id="confemail" name="confemail" placeholder="[email protected]..." autocomplete='off' required>
                <br>
                <label for="phone">Contact Number:</label>
                <input type="tel" id="phone" name="phone" pattern='[0-9]{2-3}[0-9]{2-3}[0-9]{3-4}' placeholder='000 000 0000' autocomplete='tel-national' required>
                <br>
                <label for="address"> Address:</label>
                <input type="text" id="address" name="address" placeholder='Your address...' autocomplete='address' required>
                <br>
                <label for="gender"> Gender:</label>
                <select name="gender" id="gender" autocomplete='gender' required>
                    <option value=''>Select...</option>
                    <option value="gen">Gender Diverse</option>
                    <option value="f">Female</option>
                    <option value="m">Male</option>
                    <option value="pnts">Prefer not to say</option>
                </select>
            </form>
            <button type="submit" value="Signup">
            </button>
        </div>

JS function-

function validateAndConfirm() {
    let firstname = document.getElementById('firstname').value;
    let lastname = document.getElementById('lastname').value;
    let email = document.getElementById('email').value;
    let confemail = document.getElementById('confemail').value;
    let phone = document.getElementById('phone').value;
    let address = document.getElementById('address').value;
    let gender = document.getElementById('gender').value;
    if (email == confemail) {
        alert('Your details have been submitted as below and your card will be sent out within the next 5 business days. /n First name: ' + firstname + ' /n Last name: ' + lastname + ' /n Email: ' + email + ' /n Phone ' + phone + ' /n Address: ' + address + ' /n Gender: ' + gender + '');
        return true;
    } else {
        alert('Emails do not match, please amend and try again.');
        return false;
    }
}

I am expecting this to check the emails match and if true display alert box saying “Your details have been submitted as below and your card will be sent out within the next 5 business days.
First name: firstname entered
Last name: lastname entered
Email: email entered
Phone: phone entered
Address: address entered
Gender: gender entered

If false it would ask to check emails and try again.

Change password button enabling without the password check confirmation on newpassword with comfirmpassword?

Ng-disable isn’t applying for changepassword check with new password .Even though proper directive is written to compare and check the validiaty ?

Passwrod Matching is not working.The code is written only to enable the change password on newpassword and confrimpassword being similar. But after the new password placeholder is filled the Change password Button is being enabled.

HTMl
<div class="form-group">
<label for="inputPassword" class="col-md-4 control-label">Confirm Password</label>
<div class="col-md-7 col-md-offset-right-1 input-group">
<input type="{{inputType}}" class="form-control" id="pw2" placeholder="Re enter the password" name="pw2" ng-model="forgotPwdkeys.confirmPassword" ng-required="" pw-check="pw1">
<span class="input-group-addon">
<span class="{{showHideClass}}" ng-click="showConfirmPassword()" style="cursor:pointer"></span>
</span>
</div>
<div class="msg-block passwordMask" ng-show="forgotpwdForm.$error"> <span class="msg-error" ng-show="forgotpwdForm.pw2.$error.pwmatch">Passwords don't match.</span>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-12" style="text-align:center">
<button class="btn btn-raised btn-primary" ng-disabled="forgotpwdForm.$pristine || forgotpwdForm.$invalid " ng-click="resetNewPwd();">Change</button>
</div>
</div>
directive

MainApp.directive('pwCheck', [function() {
    return {
        require: 'ngModel',
        link: function(scope, elem, attrs, ctrl) {
            var firstPassword = '#' + attrs.pwCheck;
            elem.add(firstPassword).on('keyup', function() {
                scope.$apply(function() {
                    var v = elem.val() === $(firstPassword).val();
                    console.log(v);
                    console.log('pwmatch')
                    ctrl.$setValidity('pwmatch', v);
                });
            });
        }
    }
}]);

`

Passwords don’t match.

Enquiry regarding computed properties in React/JS

I am currently following along a React tutorial to create a form, and the formdata is stored in a state, and the values of each form input is taken from that specific state. I am curious as to why square brackets are needed around the name value in the code.

I have tried googling around and apparently it has to do with computed properties, but im not really sure why name needs it, whereas value in the same line does not need it.

The part of the code in question

function handleChange(event) {
        const {name, value, type, checked} = event.target
        setFormData(prevFormData => {
            return {
                ...prevFormData,
                [name]: type === "checkbox" ? checked : value
            }
        }
            
        )
    }

Code declaring state

const [formData, setFormData] = useState({
        'email':'',
        'password':'',
        'confirm_password':'',
        'okayToEmail':false
    })

An example of one of the inputs

<input 
                    type="email" 
                    placeholder="Email address"
                    className="form--input"
                    name='email'
                    value={formData.email}
                    onChange={handleChange}
                />

New to JSON, finding JSON element total counts/occurences [closed]

I am new to JSON object manipulation. I am trying to find the count/occurences of zip codes in a json object ( I have a list of addresses in JSON data as an API call and not html properties). I am not sure or aware of how to appraoch this task. My goal is to count how many zipcodes are there in the JSON object. Please point in the direction of approach using javascript or typescript. Thanks!

I tried a map function but it is not effective or I am not aware of how to use it 🙁

JSON Strucuture:

    {
  
     "person": {
    "id": 12345,
    "name": "John Doe",
    "phones": {
      "home": "800-123-4567",
      "mobile": "877-123-1234",
      "Address": {
        "Street1": "123 Lincoln Dr",
        "Street2": "123A",
        "Zipcode": "12345",
        "State": "NY"
      }
    },
    "email": [
      "[email protected]",
      "[email protected]"
    ],
    "dateOfBirth": "1980-01-02T00:00:00.000Z",
    "registered": true,
    "emergencyContacts": [
      {
        "name": "Jane Doe",
        "phone": "888-555-1212",
        "relationship": "spouse"
      },
      {
        "name": "Justin Doe",
        "phone": "877-123-1212",
        "relationship": "parent"
      }
    ]
  }
}

Estou com problema em pegar o id que vem na URL em Next JS, usando o useParams conforme recomendado [closed]

Olá, estou com um problema em pegar o ID que vem do banco de dados pela URL, no Next JS. A versão 13 do Next é recente, muita coisa mudou e tem me deixado confuso. Meu código no front-end é o seguinte:

"use client";

import api from "@/utils/api";

import React, { useState, useEffect } from "react";
import { useParams } from "next/navigation";

import { MangaForm } from "@/components/MangaForm";

// Hooks
import useFlashMessage from "@/hooks/useFlashMessage";

export default function EditManga() {
    const [manga, setManga] = useState({});
    const [token] = useState(localStorage.getItem("token") || "");
    const { setFlashMessage } = useFlashMessage();
    const { id } = useParams();

    console.log(id);

    return (
        <section className="min-h-screen flex flex-col items-center">
            <div>
                <h1>Página Dinâmica: Detalhes do Mangá</h1>
                <h2>Editando o Mangá: </h2>
                <p>Depois da edição, os dados serão atualizados</p>
            </div>
        </section>
    );
}

Porém o id está vindo como indefinido. Fiz o teste no backend e está chegando corretamente. Já olhei a documentação do Next e dix para eu usar o useParams da forma que está em meu código, então estou perdido. Alguém consegue me ajudar?

How can I replace the code without scrollIntoView and merge two useEffects?

When the page loads, the current month should be displayed in center.
Now this code works somehow, but the requirement is to not use two useEffects and scrollIntoView.

This is initial code.

  useEffect(() => {
    const element = document.querySelector('button[data-active="true"]');
    const timer = setTimeout(() => {
      element?.scrollIntoView({
        behavior: 'auto',
        block: 'center',
        inline: 'center',
      });
    }, 300);
  
    return () => {
      clearTimeout(timer);
    };
  }, []);

  useEffect(() => {
    const element = document.querySelector('button[data-active="true"]');
    const timer = setTimeout(() => {
      element?.scrollIntoView({
        behavior: 'smooth',
        block: 'nearest',
        inline: 'center',
      });
    }, 300);

    trackEvent('Click', 'Month Tab');
    return () => {
      clearTimeout(timer);
    };
  }, [months, selectedMonth]);

Can someone please help me here.

Tried an alternative of scrollIntoView:

useEffect(() => {
  const element = document.querySelector('button[data-active="true"]');
  const container = document.documentElement; // Change this to the appropriate container element if needed
  const timer = setTimeout(() => {
    const elementRect = element.getBoundingClientRect();
    const containerRect = container.getBoundingClientRect();

    const scrollOptions = {
      left: elementRect.left + elementRect.width / 2 - containerRect.width / 2,
      top: elementRect.top + elementRect.height / 2 - containerRect.height / 2,
      behavior: 'smooth',
    };

    container.scrollTo(scrollOptions);
  }, 300);

  trackEvent('Click', 'Month Tab');
  return () => {
    clearTimeout(timer);
  };
}, [months, selectedMonth]);

But this is not working and on page load the current month is not displaying and in center.

Tried the below code but then current month does not display in center of the page on page load.


  useEffect(() => {
    const element = document.querySelector('button[data-active="true"]');
    const container = document.documentElement; // Change this to the appropriate container element if needed
    let scrollOptions;
  
    const scrollIfNeeded = () => {
      const elementRect = element.getBoundingClientRect();
      const containerRect = container.getBoundingClientRect();
  
      const shouldScroll =
        elementRect.left < containerRect.left ||
        elementRect.right > containerRect.right;
  
      scrollOptions = {
        behavior: shouldScroll ? 'auto' : 'smooth',
        left: elementRect.left + elementRect.width / 2 - containerRect.width / 2,
        top: elementRect.top + elementRect.height / 2 - containerRect.height / 2,
      };
  
      container.scrollTo(scrollOptions);
    };
  
    const timer = setTimeout(() => {
      scrollIfNeeded();
      trackEvent('Click', 'Month Tab');
    }, 300);
  
    return () => {
      clearTimeout(timer);
      if (scrollOptions && scrollOptions.behavior === 'smooth') {
        container.scrollTo(scrollOptions);
      }
    };
  }, [months, selectedMonth]);

Why is item inside .map() returning undefined

So im trying to loop the array of objects items inside <Forecast /> component but for some reason item inside .map() is returning undefined even tho when i console.log it data is there but when i try to render for ex. item.temp it crashes and says undefined…

import React from "react"

React
export default function Forecast({ items, title }) {
    console.log(items)
    return (
        <div  >
            <div className="text-white mx-8 mt-4">
                <div className="border-b ">
                    <h1 className="text-xl mb-2"> {title} </h1>
                </div>
                {
                    items.map((item, i) => {
                        console.log(item)
                        return (
                            <div key={i} className="flex justify-between my-6">
                                <div className="flex flex-col items-center">
                                    <span> {item.time} </span>
                                    <span>
                                        <img src={`https://cdn.weatherbit.io/static/img/icons/${item.icon}.png`} alt="" />
                                    </span>
                                    <span> {item.temp} </span>
                                </div>
                            </div>
                        )
                    })
                }
            </div>
        </div>
    )
}
import DefaultCitiesLI from "./DefaultCities"
import Inputs from "./Inputs"
import TimeAndLocation from "./TimeAndLocation"
import TempDetails from "./TempDetails"
import Forecast from "./Forecast"
import { useEffect, useState } from "react"
import { getCurrentData, getDailyData, getHourlyData } from "../api/weatherAPI"


export default function WeatherCard() {
    const [data, setData] = useState({})
    const [hourlyData, setHourlyData] = useState({})
    const [dailyData, setDailyData] = useState([])
    const [inputData, setInputData] = useState([])

    useEffect(() => {
        async function getData() {
            try {
                const currentHourlyData = await getHourlyData(inputData)
                const currentDailyData = await getDailyData(inputData)
                const currentWeatherData = await getCurrentData(inputData)
                setData({ current: currentWeatherData })
                // setHourlyData({ hourly: currentHourlyData})
                // setDailyData({ daily: currentDailyData })
                setHourlyData(currentHourlyData)
                setDailyData(currentDailyData)
            } catch (err) {
                console.error("Error: " + err)
                return null
            }
        }
        getData()
    }, [inputData])

    console.log(dailyData)


    return (
        <div className="flex justify-center items-center mt-8">
            <div className="bg-[#1d2d44] rounded w-[600px] px-12 pt-12">
                <ul className="flex justify-center space-x-5">
                    <DefaultCitiesLI setInputData={setInputData} />

                </ul>
                <Inputs setInputData={setInputData} />
                {data.current &&
                    <div>
                        <TimeAndLocation weatherData={data.current} />
                        <TempDetails weatherData={data.current} />

                        <Forecast items={hourlyData} title="Hourly Forecast" />
                        <Forecast items={dailyData} title="Daily Forecast" />
                    </div>
                }
            </div>
        </div>
    )
}