Paste numbers from clipboard in multiple input fields – mobile devices too

Working on the script made by @JKirchartz – https://stackoverflow.com/a/60939727/19764257
I extended it in the way to show 2 digits in each input and it works smoothly also with a different maxlength.
I tested it on mobile device but unfortunately they don’t support the copy/paste function in multiple input.
Is there a way to achieve this from mobile devices too?

<input type="number" oninput="if((this.value.length) > 2) {this.value = this.value.substring(0, 2);}">
<input type="number" oninput="if((this.value.length) > 2) {this.value = this.value.substring(0, 2);}">
<input type="number" oninput="if((this.value.length) > 2) {this.value = this.value.substring(0, 2);}">
<input type="number" oninput="if((this.value.length) > 2) {this.value = this.value.substring(0, 2);}">
<input type="number" oninput="if((this.value.length) > 2) {this.value = this.value.substring(0, 2);}">


<script>
  document.addEventListener("paste", function(e) {
    // if the target is a text input
    if (e.target.type === "number") {
      var data = e.clipboardData.getData('Text');
      // split clipboard text into single characters
      data = data.replace(/s+/g, "").split(/(?=(?:..)*$)/g);

      // find all other text inputs
      [].forEach.call(document.querySelectorAll("input[type=number]"), (node, index) => {
        // And set input value to the relative character
        node.value = data[index];
      });
    }
  });
</script>

Allow child div to be clicked through a parent div without messing with the parent div’s ::before property

I have this blue opaque box with a “flashlight” effect to see through the box for a game. The game involves looking for circles that move inside the box through a “flashlight” area.

I want to be able to have the “flashlight” effect work but allow clicks to pass through the box (parent div) in order to fire an onclick event with the circles (child divs).

CSS:

#puzzle3 {
  display: inline-block;
  text-align: center;
}

#puzzle3bg {
  display: block;
  width: 750px;
  height: 750px;
  --cursorX: 375px;
  --cursorY: 375px;
}

#puzzle3bg::before {
  content: "";
  display: block;
  width: 750px;
  height: 750px;
  position: relative;
  background: radial-gradient(
    circle 100px at var(--cursorX) var(--cursorY),
    rgba(170,255,255,.3) 0%,
    rgba(170,255,255,.6) 80%,
    rgba(170,255,255,1) 100%
  );
  z-index: 10;
}

.p3correctCircle {
  display: inline-block;
  position: absolute;
  background: #00FF00;
  border-radius: 50%;
  width: 50px;
  height: 50px;
  transition-duration: 600ms;
  z-index: 0;
}

.p3wrongCircle {
  display: inline-block;
  position: absolute;
  background: #FF0000;
  border-radius: 50%;
  width: 50px;
  height: 50px;
  transition-duration: 600ms;
  z-index: 0;
}

HTML:

<div id="puzzle3">
  <div id="puzzle3box">
    <div class="p3correctCircle"></div>
    <div class="p3correctCircle"></div>
    <div class="p3correctCircle"></div>
    <div class="p3wrongCircle"></div>
    <div class="p3wrongCircle"></div>
    <div class="p3wrongCircle"></div>
    <div class="p3wrongCircle"></div>
    <div class="p3wrongCircle"></div>
  </div>
  <div id="puzzle3bg"></div>
</div>

JS:

function updateCursor(e) {
  var x = e.offsetX
  var y = e.offsetY
  document.getElementById("puzzle3bg").style.setProperty('--cursorX', x + 'px')
  document.getElementById("puzzle3bg").style.setProperty('--cursorY', y + 'px')
}

document.getElementById("puzzle3bg").addEventListener('mousemove', updateCursor)
document.getElementById("puzzle3bg").addEventListener('touchmove', updateCursor)

// I took this from someone else's codepen so I'm not sure how to modify it

Whenever I try the pointer-event stuff, either the “flashlight” effect doesn’t work or the child divs are still not working. But maybe I’ve been doing it wrong, so I’d appreciate any help.

XPATH All Selectors Return Null

I am wanting to know if it is possible to pull Xpath on the following website page(s)

https://directories.apps.realtor/memberDetail/?personId=4165309&officeStreetCountry=US&memberLastName=BROWN

I keep getting the error “All Selectors Return Null”. I would like to retrieve: NAME, BUSINESS EMAIL, OFFICE, OFFICE WE PAGE, OFFICE ADDRESS and OFFICE PHONE if possible. Thanks in advance

I tried to use an Xpath Add-On from Google Sheets. I’ve successfully used the program with other sites but for some reason I can’t get it to work on this particular site.

i want to use an variable inside of a regex

i have a variable that i need to put into a regex but i am getting this error:

Invalid regular expression: //^-?(0|[1-9]*)(+variable+[2-9]*)?$//: Nothing to repeat 

this is my variable:

const variable =getDocument()

this is the regex

/^-?(0|[1-9]*)(+variable+[2-9]*)?$/

i tried like this:

const reg = new RegExp(`/^-?(0|[1-9][0-9]*)(+variable+[0-9]*)?$/`)

TypeScript error when this command “tsc index.ts” ” shows is not digitally signed”

Trying to learn TypeScript but I get an error

PS C:UsersjogodDesktopTypeScript> tsc index.ts
enter image description here

tsc : File C:UsersjogodAppDataRoamingnpmtsc.ps1 cannot be loaded. The
file C:UsersjogodAppDataRoamingnpmtsc.ps1 is not digitally signed. You
cannot run this script on the current system. For more information about
running scripts and setting execution policy, see about_Execution_Policies
at https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1

  • tsc index.ts
  •   + CategoryInfo          : SecurityError: (:) [], PSSecurityException      
      + FullyQualifiedErrorId : UnauthorizedAccess
    
    

I’m expecting that this command tsc index.ts will create another file of “index.js”

i am having issue in connecting my socket chat to namecheap server [closed]

is there any body that has hosted socket chatroom on Namecheap before. please I need your help in connecting my JS to my PHP socket server to Namecheap hosting platform. this is my site ngnetads.com

I really need a solution before my hosting get expired

ON my localhost machine the code is working find while on a live website it is not working correctly.

let socket = new WebSocket("ws://192.168.43.205:8060");

Access the URL of an iframe on a different doman using JavaScipt? Everyone says it is impossible but it isn’t?

First a short background/context: I’m using AppleScript to control a browser (Chrome), mostly fill in forms. Now I have encountered an odd form, where part of it is in the “main” webpage, part of it is in an iframe (they are, codewise, of course two different forms but from a user perspective everything seems to be one form) linked from the main page. The main page and the iframe are on completely different domains. According to multiple questions and answers here on SE you can’t access the URL of an iframe using JavaScript if the iframe is on a different domain. Two examples:

How to get the current URL (not the src) of an iframe?

Get current URL from IFRAME

However, I just executed document.documentElement.outerHTML on the page I described in the first paragraph and in the source code that was returned it was easy to find several iframe-tags, including their URLs, e.g.,

<iframe src="https://www.googletagmanager.com/ns.html?id=GTM-KJ476ZB" height="0" width="0" style="display:none;visibility:hidden;">

This should be reasonably easy to extract using a regular expression, so why is this information blocked from access if you want to use CSS (?) classes, IDs etc?

Anyway, my ultimate goal is to write a script that extracts an image from a specific iframe, download that image, process the image locally and finally uploads it and inserts it into a field in the form in the iframe (as well as enter some text in the fields in the parts of the form that are part of the main page).

I have done similar things before, usually by opening the iframe in a new tab which avoids all cross site problems, but there are some issues here:

  1. The iframe doesn’t work if I open its URL in a separate window. Everything looks fine, but the click I have to perform to make the image I want to download appear, doesn’t work when the iframe isn’t embedded in another page. This prevents me from downloading the image using this method (opening in the iframe URL in its own window and treat it like the regular page it actually is).

  2. Then is the next problem that I can’t access the iframe when it is part of the main page when I want to submit data to it. I have done things like this in Selenium before and in Selenium it is easy to change focus from the main page to the iframe. Can something similar be done using JavaScript and/or Chrome’s built in support for AppleScript?

2,5 Why does browsers allow access to iframes when using Selenium but not when using JavaScript? Please note my usecase again: I am writing an AppleScript to automate some tasks in a browser. This will all be executed locally, so is exactly the same situation as you have when using Selenium (and Selenium also allows JavaScript to be executed by the browser). I just don’t understand why a browser doesn’t allow me to (basically) paste whatever code I want in the browser console and execute it. After all, it is my computer and I do it intentionally (as opposed to if a random webpage on internet includes malicious code that is executed in the background). It is no different from executing a bash script in the terminal (which of course could be very dangerous if you do it blindly).

When I wrote the above another question appeared: can AppleScript interact with Selenium, and could that be a solution to the iframe problem?

Issue importing matplotlib in in html code (HTML Beginner)

While trying to run a python program in my html script, I ran into the following error:

JsException(PythonError: Traceback (most recent call last): File "/lib/python3.10/site-packages/_pyodide/_base.py", line 429, in eval_code .run(globals, locals) File "/lib/python3.10/site-packages/_pyodide/_base.py", line 300, in run coroutine = eval(self.code, globals, locals) File "", line 2, in ModuleNotFoundError: No module named 'matplotlib' )

Where line 2 says

from matplotlib import pyplot as plt

The script runs fine in my python editor, leading me to believe that the issue has to do with it being in an html file.
I assume the issue may be related to where matplotlib was imported?
Any help is appreciated.

How do I trigger an @keyframe animation on scroll?

I have an @keyframe animation that rotates a circle on its x axis from 0 to 90 and then from 90 back to 0 degrees again. My goal is: when the user scrolls down the page, the rotation of the circle will simultaneously increase incrementally with the pace of the user’s scrolling until the scroll count reaches 160 down the page where the rotation of the circle will peak at 90 degrees. As the user continues to scroll down past 160, I want the circle to incrementally rotate back to 0 degrees once the user reaches 280 down the page.

So far I have tried putting the @keyframes into a class called Animation and then using classList.add in the JavaScript to call that class but this did not work.

Can anyone help? Thanks in advance.
P.S. I would like to use only JavaScript no jQuery.

function Ani(){
  Ani.classList.add('Animation');  
}
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
section{

  height: 100vh;
}
html, body {
  height: 100%;
}
.one{
  background-color: rgb(105, 170, 254);
}
#divItem {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;

  position: relative;
}

.triangle, .circle, .rectangle {
  position: absolute;


}


.circle {
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
    animation: moving;
    animation-duration: 2s;
  }

  





.Animation{
@keyframes moving {
  0%{
    transform:rotateX(0deg);
    transform-origin: 30% 50%;
  }
  50%{
    transform:rotateX(90deg);
    transform-origin: 30% 50%;
  }
  100%{
    transform: rotateX(0deg);
  }
}
}


.two{
  background-color: brown;
}
.three{
  background-color: bisque;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Scroll-Trigger</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
  <section class="one">

<div id="divItem">
   
    <img src="triangle.svg" class="triangle" width="150px" />
    <div class="Animation">
    <img src="circle.svg" class = "circle" width="150px"/>
  </div>
    <img src="rectangle.svg" class="rectangle" width="150px"/> 
</div>

</section>  
<section class="two">
   
</section>

<section class="three">
  
</section>
<script src="index.js"></script>

</body>
</html>

Javascript get style character by character in an element

I have a dynamically created div with styled characters such as:
<div>Hello <b>J</b>oe</div>
and I am trying to figure out which characters are styled (in this case the J).

I have already tried window.getComputedStyle() but I was unsuccessful in getting the style character by character.

Bigger example:

<div id="testing">H<b>i</b> I <b>a</b>m b<b>o</b>b</div>

Expected output:
getDivStyle(“testing”) =>

H: false
i: true

I: false

a: true
m: false

B: false
o: true
b: false

Thank you for your help!

How to do private routes with the useRoutes hook in React

I’m trying to build a private and public route in React, and I’m using the useRoutes hook. I didn’t know how to do this, already exist an answer to this question on Stack Overflow. However, it was just a copy and paste of some code. I really want to really learn how I can afford this.

I tried using the other answer, but it didn’t help me much. If anyone can assist, I would be extremely grateful. This is the code I wrote.

import Home from "../pages/home"
import Items from "../pages/itens"
import Login from "../pages/login"
import Printers from "../pages/printers"
import { AuthContext } from "../contexts"
import { useContext } from "react"
import { Navigate } from "react-router-dom"

function Routes() {

    const { sessionContextValue } = useContext(AuthContext)
    const { isAuth } = sessionContextValue

    const routes = [
        {
            path: '/',
            element: isAuth ? <Home /> : <Navigate to={'/login'} replace/>,
        },
        {
            path: '/printers',
            element: <Printers />
        },
        {
            path: '/items',
            element: <Items />
        },
        {
            path: '/login',
            element: <Login />
        }
    ]

    let router = useRoutes(routes)
    return router
}

export default Routes

Is there a way to view/use web developer tools by plugging an android phone into a Windows 11 PC?

I’m not a mobile app developer but I do develop an intranet which has an app which was created for us. The app uses web controls to display a mobile HTML interface within the intranet. Every now and then we’ll see a bug which may be related to a javascript or HTML error. I’m wondering if there is some sort of emulator which will allow me to check for errors in the same way we do for Chrome/Edge etc. The process being to right-click, click on ‘Inspect’ and then look at what we need to look at (usually in the Elements, Network or Console tabs). I’m aware of emulators but not sure if any can provide this sort of connection. When I had a Mac I was able to do this with iPhone and Safari.

The specific issue is with the latest Pixel phone and a file upload button that won’t work. I’d like to be able to check if there’s a javascript error happening when the page loads and/or whether the click on the upload button is triggering an error.

We’ve tested on other Android phones but it seems to only be the latest Pixel that doesn’t want to work.

React keeps re-rendering my components that i made by mapping over an object.entries(useState variable)

i have written code in react js and it works (it renders a simple table) but the table elments keep rerendering every second and when i try to highlight something it unhighlights immediately

this is a react table that basically pulls from lichess api
it renders a table but the the td and trs keep refreshing constantly

i tried this

import './Recent.css';
import { React, useState, useEffect, useMemo } from 'react';
import { v4 as uuidv4 } from 'uuid';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faSort, faSortUp, faSortDown } from '@fortawesome/free-solid-svg-icons'

import * as fetch from 'node-fetch';

function Recent() {
  const [ratings, setRatings] = useState({});
  const [headers, setHeaders] = useState([""]);
  const [loaded, setLoaded] = useState(false);
  const [vState, setVState] = useState('default');
  const [dState, setDState] = useState('default');
  const [rState, setRState] = useState('default');

  const fetchRatings = () => {
    fetch('lichesslinkthatyoudontgettosee')
      .then (response => {
        return response.json()
      })
      .then (data => {
        setRatings(data);
        setHeaders(["Variant", "Date", "Rating"]);
        setLoaded(true);
      });
  }

  useEffect(() => {
    fetchRatings()
  }, []);

  function vCycle(vState) {
    if (vState === 'default') {
        setVState('dsc');
        setDState('default');
        setRState('default');
    } else if (vState === 'dsc') {
        setVState('asc');
    } else {
        setVState('default');
    }
  }

  function dCycle(dState) {
    if (dState === 'default') {
        setDState('dsc');
        setVState('default');
        setRState('default');
    } else if (dState === 'dsc') {
        setDState('asc');
    } else {
        setDState('default');
    }
  }

  function rCycle(rState) {
    if (rState === 'default') {
        setRState('dsc');
        setVState('default');
        setDState('default');
    } else if (rState === 'dsc') {
        setRState('asc');
    } else {
        setRState('default');
    }
  }
  return (
    <div className="container" style={{display: loaded ? 'flex' : 'none'}}>
      <h2>Most Recent</h2>
      <table>
        <thead>
          <tr>
            <th onClick={() => vCycle(vState)}>{headers[0]} <span><FontAwesomeIcon fixedWidth transform="shrink-3" icon={vState === 'default' ? faSort : vState === 'asc' ? faSortUp : faSortDown} /></span></th>
            <th onClick={() => dCycle(dState)}>{headers[1]} <span><FontAwesomeIcon fixedWidth transform="shrink-3" icon={dState === 'default' ? faSort : dState === 'asc' ? faSortUp : faSortDown} /></span></th>
            <th onClick={() => rCycle(rState)}>{headers[2]} <span><FontAwesomeIcon fixedWidth transform="shrink-3" icon={rState === 'default' ? faSort : rState === 'asc' ? faSortUp : faSortDown} /></span></th>
          </tr>
        </thead>
        <tbody>
           {Object.values(ratings).filter(o => o.points.length).map((item) => {
                return (
                  <tr key={uuidv4()}>
                    <td className="variant">{item.name}</td>
                    <td className='date'>{item.points.at(-1)[1] + 1 + "/" + item.points.at(-1)[2] + "/" + item.points.at(-1)[0].toString().slice(2, 4) }</td>
                    <td className='rating'>{item.points.at(-1)[3]}</td>
                  </tr>
                )
           }) ?? null}
        </tbody>
      </table>
    </div>
  );
}

// const displayInfo = () => (
  
// )

export default Recent;

it keeps refreshing all the trs and tds
how can i fix this

How to update timestamp only after order data is loaded?

I have a task where I need the timestamp to be updated after the orders in the application have completed loading. For more context, this is a website I’m working on that has an ‘Orderbook’ tab. Within the “Orderbook’ tab, is an ag-grid where orderbook orders are loaded. Below is the HTML code regarding the timestamp:

<div class= "col d-flex">
  <div class="mr-auto">h4>Orderbook</h4></div>
  <div class="py-1 px-1"><span class="last-refreshed-text"> Last Updated On:
       {{lastRefreshed | date: 'MM dd hh:mm:ss a'}} </span></div>
</div>
<div class="py-1 px-1"><button mat-raised-button color="blue" title="Refresh Orders" 
(click) ='refreshECM()' [disabled]="lastRefreshedInProgress">
   <div class="my-auto"
      <mat-spinner diameter= "16" *ngIf="lastRefreshedInProgress"></mat-spinner>
      Refresh
   </div>
 </button>
</div>

Currently, if I navigate between tabs on the website such as “Orderbook” or “Roadshow Schedule”, the timestamp persists. Once I’m back on the Orderbook tab, the timestamp hasn’t updated which is what’s intended. The timestamp also refreshes once I click the refresh button or when I refresh from the browser itself as intended. However, when I click the refresh button created, the timestamp refreshes immediately even though the data hasn’t completed loading. This is the setup that I currently have:

    ngOnInit() {
  // Clear the stored timestamp when the page is refreshed or closed
  window.onbeforeunload = () => {
    sessionStorage.removeItem('lastRefreshed');
  };

  this.showIndicationRoadshow = this.hasRoadshowData;
  // Retrieve the stored timestamp from local storage, if available
  const storedLastRefreshed = sessionStorage.getItem('lastRefreshed');
  if (storedLastRefreshed) {
    this.lastRefreshed = new Date(storedLastRefreshed);
  } else {
    this.lastRefreshed = new Date();
  }
}
    refreshECM() {
  this.lastRefreshed = new Date();
  this.lastRefreshedInProgress = true;
  if (this.gridApi) {
    this.gridApi.showLoadingOverlay();
  }
  this.orderbookLoadingTimeout = 0;
  this.refreshOrderBook.emit(true);
sessionStorage.setItem('lastRefreshed', this.lastRefreshed.toISOString());
}

ngOnDestroy(){
sessionStorage.setItem('lastRefreshed', this.lastRefreshed.toISOString());
} 

I thought I could update the timestamp where the order data is processed so within this but I’m not sure :

ngOnChanges(changes: SimpleChanges) {
  if (changes.orderData) {
    setTimeout(() => {
      this.rowDataECM = this.orderData;
      this.orderbookLoadingTimeout = 500;
      this.lastRefreshedInProgress = false;
    }, this.orderbookLoadingTimeout);
  }
}

If I work within ngOnChanges to update the timestamp after the orders have finished loading with this code, the timestamp doesn’t freeze when I’m navigating in between tabs and return to the ‘Orderbook’ tab:

ngOnChanges(changes: SimpleChanges) {
    if (changes.orderData) {
      setTimeout(() => {
        this.rowDataECM = this.orderData;
        this.orderbookLoadingTimeout = 500;
        this.lastRefreshedInProgress = false;

        // Update the timestamp after the orders have finished loading
        this.lastRefreshed = new Date();
        sessionStorage.setItem('lastRefreshed', this.lastRefreshed.toString());
      }, this.orderbookLoadingTimeout);
    }
  }

So how can I have it so that the timestamp updates once the orders are finished loading but that if I am to navigate to another tab on the page, the timestamp shouldn’t update? Currently, I’ve only figured out a way for either the timestamp to freeze between tabs + timestamp refresh automatically despite orders still loading or timestamp refreshing after orders completed loading + timestamp also refreshes when navigating between tabs.

Chained selectors not correct in querySelector [closed]

I’m not understanding why my chain of querySelector is invalid. I’m converting these from jQuery, but from what I’m reading this is totally doable.

This is my incorrect code…

document.querySelector(":button[name='checkout'], a[href$='checkout'], form[action='/cart'], input[name='checkout']").addEventListener('click', event => {
  console.log("do something")
})

It errors with:

Uncaught DOMException: Document.querySelector: ‘:button[name=’checkout’], a[href$=’checkout’], form[action=’/cart’], input[name=’checkout’]’ is not a valid selector

What’s wrong with my code?