How can I edit a todo list on the same input where add todo in React?

I’m a begginer in React js, I have the code of a project taken from YouTube, the issue is that when I edit a task, I want to edit it in the same input where I add the tasks.

Actually I have no idea how to achieve this, I wish someone could help me

Here I got the main component:
`import React from ‘react’;
import ‘./App.css’;
import TodoList from ‘./components/TodoList’;

function App() {
  return (
    <div className='todo-app'>
      <TodoList />
    </div>
  );
}

export default App;`


     Todo.jsx component:
`import React, { useState } from "react";
import { RiCloseCircleLine } from "react-icons/ri";
import { TiEdit } from "react-icons/ti";
import TodoForm from "./TodoForm";

const Todo = ({ todos, updateTodo, completeTodo }) => {
  const [edit, setEdit] = useState({
    id: null,
    value: "",
  });

  function updateSubmit(value) {
    updateTodo(edit.id, value);
    setEdit({
      id: null,
      value: "",
    });
  }

  if (editar.id) {
    return <TodoForm edit={edit} onSubmit={updateSubmit} />;
  }

  return todos.map((todo, index) => (
    <div
      className={todo.isComplete ? "todo-row complete" : "todo-row"}
      key={index}
    >
      <div key={todo.id} onClick={() => completeTodo(todo.id)}>
        {todo.text}
      </div>
      <div className="icons">
        <TiEdit
          onClick={() => setEdit({ id: todo.id, value: todo.text })}
          className="edit-icon"
        />
      </div>
    </div>
  ));
};

export default Todo;`


TodoList.jsx component:
`import React, { useState } from "react";
import TodoForm from "./TodoForm";
import Todo from "./Todo";

function TodoList() {
  const [todos, setTodos] = useState([]);

   const addTodo = (todo) => {
     const newTodos = [todo, ...todos];

    setTodos(newTodos);
  };

  const updateTodo = (todoId, newValue) => {
    if (!newValue.text || /^s*$/.test(newValue.text)) {
      return;
    }

    setTodos((prev) =>
      prev.map((item) => (item.id === todoId ? newValue : item))
    );
  };

  const completeTodo = (id) => {
    let updatedTodos = todos.map((todo) => {
      if (todo.id === id) {
        todo.isComplete = !todo.isComplete;
      }
      return todo;
    });
    setTodos(updatedTodos);
  };

  return (
    <React.Fragment>
      <h1>What's the Plan for Today?</h1>
      <TodoForm onSubmit={addTodo} />

      <Todo
        todos={todos}
        completeTodo={completeTodo}
        updateTodo={updateTodo}
      />
    </React.Fragment>
  );
}

export default TodoList;`


 TodoForm component:
`import React, { useState, useEffect, useRef } from "react";

function TodoForm({ editar, onSubmit }) {
  const [input, setInput] = useState(edit ? edit.value : "");

  const inputRef = useRef(null);

  useEffect(() => {
    inputRef.current.focus();
  });

  const handleChange = () => {
    setInput(inputRef.current.value);
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    if (!inputRef.current.value || /^s*$/.test(inputRef.current.value)) {
      return;
    }

    onSubmit({
      id: Math.floor(Math.random() * 10000),
      text: inputRef.current.value,
    });
    setInput("");
  };

  return (
    <form onSubmit={handleSubmit} className="todo-form">
      <React.Fragment>
        <input
          placeholder={edit ? "Update your elemento" : "Add a Todo"}
          value={input}
          onChange={handleChange}
          name="text"
          className={edit ? "todo-input edit" : "todo-input"}
          ref={inputRef}
        />
        <button
          onClick={handleSubmit}
          className={edit ? "todo-button edit" : "todo-button"}
        >
          Update
        </button>
      </React.Fragment>
    </form>
  );
}

export default TodoForm;
`

       

[edit task in another input](https://i.stack.imgur.com/ajma4.png)

[different input](https://i.stack.imgur.com/52R2k.png) 

Is it possible to auto-import files with webpack or React so that I don’t need to `import` every time

I very often need to write:

<div style={{display:'flex'}}>
  ...
</div>

However, I’d ideally just write:

<Row>
  ...
</Row>

But I don’t want to need to import Row from './Row' every time.
What’s the easiest way to accomplish this?

I’m happy to disable linting for specific variables.
Is there something I can do to webpack config to make it accessible to every React file?

How to perform multiple HTTP requests with unique IP addresses from my local

I am trying to call our homepage www.123.com 10 times simultaneously with unique IP addresses.

We are having issues with GTag Analytics and I am trying to confirm if I can call our homepage 10 times and it will register on GTAG, or not.

I have found 2 posts on load balancing testing with unique IP addresses, which would allow me to do this

One using K6 and the other using JMeter.

k6 -> https://stackoverflow.com/questions/72016444/websites-load-testing-using-k6-from-multiple-ip-addresses
but the comment suggests it wont work on a laptop you need more Network cards (which aligns with my findings below)

I tried using JMeter and selecting ‘Number of Threads (users) and increasing this to 10, these tests passed, but it only showed as one user on GTag, because of the same IP im assuming.

I found this post which talks about this and suggests Spoofing(adding multiple IP addresses to your IP4) and running with JMeter which should make a call for each IP address,

https://stackoverflow.com/questions/41049686/how-to-create-a-load-test-with-unique-ip-addresses

But this didnt work. The article states 'In the case of a DHCP-assigned address, the IP alias feature won’t work and you won’t be able to add extra IP addresses to your network adapter.'

As I am running through my home router which would be using DHCP, this would not work

Any replies very much appreciated thank you

(I tagged C# and JS also incase theres anything thats available that I am unaware of thank yoU)

Problems with appscript conditional statements

I have a sheet that has radio buttons in 1 row from columns D to I. In columns B and C there are 2 checkboxes that I am using as a tally to increase and decrease values in different cells. What I want to acheive is, when a radio button is selected and is true(when a checkbox is checked), the increasing and decresing buttons/checkboxes change their location to increment and decrement the value at that location.
My problem is when I format the conditional statements, the increasing and decreasing buttons don’t work. Help would be very much appreciated, I am new to coding so sometimes the syntax can be confusing. Below is what I have tried.

const RADIO_COLUMNS = ["D","E","F","G","H","I"];

function onEdit(e) {
  const sheet = e.range.getSheet();
  const row = e.range.rowStart;
  const col = e.range.columnStart;
  const val = sheet.getRange(row,col).getValue();

  const colLetter = String.fromCharCode(64 + col);

  if (val == true && RADIO_COLUMNS.includes(colLetter)) {
    RADIO_COLUMNS.filter(column => column !== colLetter)
      .forEach(column => sheet.getRange(column + row).uncheck());
  }
  //if (!e) throw "Do not run from editor";
    if (RADIO_COLUMNS['D']='TRUE'){
   incrementAndDecrementD(e);
    } 
    else if (RADIO_COLUMNS['E']='TRUE') {
       incrementAndDecrementE(e);
    }
    else if (RADIO_COLUMNS['F']='TRUE') {  
      incrementAndDecrementF(e);
    }
//if radio buttons true then function incrementandDecrement(e)
}

}

function incrementAndDecrementD(e){
  const src = e.source.getActiveSheet();
  const r = e.range;

  if (src.getName() != "b" || r.columnStart < 2 || r.columnStart > 3) return;

  let out;
  if (r.columnStart == 2){
    out = r.offset(0,2);
    out.setValue(out.getValue()+1)
  } else {
    out = r.offset(0,1);
    out.setValue(out.getValue()-1)
  }

  r.setValue("FALSE");
}

function incrementAndDecrementE(e){
  const src = e.source.getActiveSheet();
  const r = e.range;

  if (src.getName() != "b" || r.columnStart < 2 || r.columnStart > 3) return;

  let out;
  if (r.columnStart == 2){
    out = r.offset(0,3);
    out.setValue(out.getValue()+1)
  } else {
    out = r.offset(0,2);
    out.setValue(out.getValue()-1)
  }

  r.setValue("FALSE");
}

function incrementAndDecrementF(e){
  const src = e.source.getActiveSheet();
  const r = e.range;

  if (src.getName() != "b" || r.columnStart < 2 || r.columnStart > 3) return;

  let out;
  if (r.columnStart == 2){
    out = r.offset(0,4);
    out.setValue(out.getValue()+1)
  } else {
    out = r.offset(0,3);
    out.setValue(out.getValue()-1)
  }

  r.setValue("FALSE");
}

function incrementAndDecrementG(e){
  const src = e.source.getActiveSheet();
  const r = e.range;

  if (src.getName() != "b" || r.columnStart < 2 || r.columnStart > 3) return;

  let out;
  if (r.columnStart == 2){
    out = r.offset(0,5);
    out.setValue(out.getValue()+1)
  } else {
    out = r.offset(0,4);
    out.setValue(out.getValue()-1)
  }

  r.setValue("FALSE");
}

function incrementAndDecrementH(e){
  const src = e.source.getActiveSheet();
  const r = e.range;

  if (src.getName() != "b" || r.columnStart < 2 || r.columnStart > 3) return;

  let out;
  if (r.columnStart == 2){
    out = r.offset(0,6);
    out.setValue(out.getValue()+1)
  } else {
    out = r.offset(0,5);
    out.setValue(out.getValue()-1)
  }

  r.setValue("FALSE");
}

function incrementAndDecrementI(e){
  const src = e.source.getActiveSheet();
  const r = e.range;

  if (src.getName() != "b" || r.columnStart < 2 || r.columnStart > 3) return;

  let out;
  if (r.columnStart == 2){
    out = r.offset(0,7);
    out.setValue(out.getValue()+1)
  } else {
    out = r.offset(0,6);
    out.setValue(out.getValue()-1)
  }   

  r.setValue("FALSE");
}

React Native Expo published app not displaying logo properly

I published an app on Google Play. Everywhere the logo is fine, but when I install app on physical device from Google Play, it does not show the full logo of my app. Weird behaviour, kind of like it zooms in, cuts off the edges.
I suspect it’s something to do with my app.json, I tried with a bunch of image sizes, maybe I am not trying correct ones.

"icon": "./192.png",
"android": {
  "adaptiveIcon": {
    "foregroundImage": "./Icon.png",
    "backgroundImage": "./BG.png"
},

This is the latest code I tried.
192.png is basically 192 x 192 image.
Icon.png is the icon image by itself (not including the background of the icon).
BG.png is the background color of the image.

How I expected it to show up once installed
How it shows up once installed

I tried using 512 x 512 png image in the icon field as well, but that did not work either.

Identifier ‘web3’ has already been declared despite web3 is undefined

I am connecting a html page to a Solidity contract and get contradicting errors.
If I comment out the line const web3 = new Web3(window.ethereum); the code works and it says web3 is undefined no error.
But when I uncomment const web3 = new Web3(window.ethereum); I get Identifier 'web3' has already....

What am I missing here?

Complete code here https://guess-number-q57u.onrender.com/

<script>//<- line 32
  if (typeof web3 === 'undefined') {
    console.log("web3 is undefined"); //prints-->web3 is undefined
  } else {
    console.log("web3 variable is defined and" + " value is " + web3);
  }

  //const web3 = new Web3(window.ethereum);//<-- when I uncomment this line I get: despite above web3 is undefined
  //(index):32 Uncaught SyntaxError: Identifier 'web3' has already been declared (at (index):32:9)

Finding a point exactly between two points on a map at a specific distance from one point

I’ve been working on a mapping project and encountered a problem where I need to find a point exactly between two given points on a map, at a specific distance from one of the points. I’ve tried various approaches, but haven’t been able to achieve the desired result.

I’ve researched and found a formula to calculate the distance between two points on the Earth’s surface, and I’ve adjusted it accordingly. Now, I’m trying to use this formula to find a third point on the map that lies exactly between the two given points and is at a specific distance from one of them.

Here’s what I’ve tried so far:

// Variable declare
let start_get_lat = 31.5387761;
let start_get_lng = 72.9696664;
let end_get_lat = 31.569235;
let end_get_lng = 72.983557;
let center = {lat: Number(start_get_lat), lng: Number(start_get_lng)};
let endLocation = {lat: Number(end_get_lat), lng: Number(end_get_lng)};

Calculate distance bw two points and

// calculate distance function 
const distance = calculateDistance(lat1, lon1, centerLat, centerLon);

Get point bwtween function and usage

function getPointBetween(startLat, startLng, endLat, endLng, distance) {
    const earthRadius = 6371000; // Earth's radius in meters

    // Convert latitudes and longitudes from degrees to radians
    const lat1 = startLat * Math.PI / 180;
    const lon1 = startLng * Math.PI / 180;
    const lat2 = endLat * Math.PI / 180;
    const lon2 = endLng * Math.PI / 180;

    // Calculate the angular distance between the points
    const delta = distance / earthRadius;

    // Calculate the intermediate point
    const A = Math.sin((1 - delta) * Math.PI / 2) + Math.sin(delta * Math.PI / 2) * Math.cos(lat1) * Math.cos(lat2);
    const B = Math.sin(delta * Math.PI / 2) * Math.sin(lon2 - lon1) * Math.cos(lat2);
    const C = Math.atan2(B, A);
    const lat3 = Math.asin(A * Math.sin(lat1) + B * Math.sin(lat2)) * 180 / Math.PI;
    const lon3 = (lon1 + Math.atan2(Math.sin(lon2 - lon1) * Math.cos(lat2), Math.cos(lat1) * Math.sin(lat2) + Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1))) * 180 / Math.PI;

    return { lat: lat3, lng: lon3 };
}

let anyDistance = distance - 1000;
const pointBetween = getPointBetween(start_get_lat, start_get_lng, end_get_lat, end_get_lng, anyDistance);
let bwMarker = new google.maps.Marker({
    position: pointBetween,
    map: map,
    title: "Center",
    fillColor: 'blue', //
});
console.log(pointBetween);

However, while this function returns a point between the two coordinates, it does not guarantee that the point lies exactly on the line segment between them at the specified distance. The goal is to achieve a precise displacement from one of the given points.

I’m looking for insights or alternative manual calculation methods to achieve this precise displacement between two coordinates without using google map, as I need a solution that can be implemented in both front-end and back-end environments.

Any suggestions or advice would be greatly appreciated. Thank you for your time and assistance!

How to get an Object value in a single line expression in Javascript

So i have this below object and i want to return true or false based on the value.

obj =   
    {
        "closed": 
            {
                "CS1710897175876283": true
            },
        "unpaid": 
            {
                "CS1711279916237480": false, 
                "CS1711497275526501": true
            }
    }

console.log(obj['closed']) // {"CS1710897175876283": true}, this is fine
console.log(obj['closed']['CS1710897175876283']) // got error "TypeError: Cannot convert undefined value to object"

status={obj['unpaid']['CS1711279916237480'] ? "checked" :  "unchecked"} // got an error as well 

How can get return true or false in just one line.

How do I resize an image while keeping the aspect ratio if my parent container size is unknown, and dynamic

I’m making an image gallery. While working on the feature that brings the image to the full size of the browser window I realized that I can’t specifically set the size of the parent element that the img belongs to so it won’t play nice / fit how I want it to fit. I generally use the below trick for making images resize nicely while keeping the aspect ratio, staying centered nicely and not flowing over it’s parent element.

.keep-img-ratio {
    max-width: 100%;
    max-height: 100%;
    margin: auto;
  }

How do you solve this in a situation where the parent element of the img will be the size of the window which is dynamic and make the auto margin work?

Parse Irregular table

enter image description here

Notice this complex table. For many of the rows on the left like “finite forms”, “past”, and “future”, they have “rowSpan” equal to something greater than 1.

If I wanted to parse a simple table that has no row (or col-)Span attributes, then I would simply get table.rows and get the index of each row as the column, and determine what categories the cells belong to based on that.

The rowSpan and colSpan attributes of this table make things more complex, because if I get table.rows then the row at the beginning of “past” really has “past” then “first” then the next word (in this case דַּשְׁתִּי‎).

If that pattern repeated for the rows after, then it would be fine because I would be able to determine what category and sub cateogry of the row each cell belonged to (in this case it would be that the word דַּשְׁתִּי‎ (and דַּשְׁנוּ‎ on that same row) would be under the row categories of “past” and “first” (as well as each in it’s own column cateogry, for דַּשְׁנוּ‎ plural [m,f] and for דַּשְׁתִּי‎ singular [m, f])).

However, with rowSpan set to 3 in the “past” row area, the next row under “first” (“second” in this case) is the first element of the new array, even though the “past” cell really preceeds it in the HTML (and in the way I want to parse the table in JavaScript).

To simply the question:

I need to parse a complex table, in JavaScript, which may contain rowSpan and colSpan attributes.

My goal is to get the inner cells of the table and it’s corresponding row and columns categories (in this case, there are two categories for both row and column (skipping the “non-finite forms” row at the top), I want a result as an array of objects where each object represents an inner cell, containing meta information about the row categories and column categories that cell belongs to.

In our example of the word דַּשְׁתִּי‎, the result should be some kind of JavaScript object (in an array) like this

content: דַּשְׁתִּי‎

row: 1 (assuming we start counting from the first inner word after categories start)

column: 1

rowCategories: [past, first]

columnCategories: [singular, [m,f]]

For the next word, the result would be almost the same except the columnCategories would be [plural, [m, f]].

And so too for all of the other inner cells.

Ideally I am looking for a function that takes in arguments specifying how many row and column categories there are (in this case, 2 each), dynamically being able to parse a table with any amount of them.

I have been trying to figure this out, but not able to just think how to properly parse the table to represent the row categories in front as well as the column categories properly to be able to cross reference them and organize them properly, given the rowSpan and colSpan attributes.

How to fix the error Class extends value undefined is not a constructor or null

When importing

import { useUmi } from '../../../../components/mint/umi';
import { useSplMinter } from '../../../../components/mint/tokenMinting';

I get an error in the token creation file.
Error:

Class extends value undefined is not a constructor or null
TypeError: Class extends value undefined is not a constructor or null
    at ./node_modules/@metaplex-foundation/mpl-token-metadata/dist/src/errors.js (http://192.168.0.222:3000/static/js/bundle.js:1873:40)
    at options.factory (http://192.168.0.222:3000/static/js/bundle.js:118516:31)
    at __webpack_require__ (http://192.168.0.222:3000/static/js/bundle.js:117945:32)
    at fn (http://192.168.0.222:3000/static/js/bundle.js:118174:21)
    at ./node_modules/@metaplex-foundation/mpl-token-metadata/dist/src/hooked/metadataDelegateRoleSeed.js (http://192.168.0.222:3000/static/js/bundle.js:20702:18)
    at options.factory (http://192.168.0.222:3000/static/js/bundle.js:118516:31)
    at __webpack_require__ (http://192.168.0.222:3000/static/js/bundle.js:117945:32)
    at fn (http://192.168.0.222:3000/static/js/bundle.js:118174:21)
    at ./node_modules/@metaplex-foundation/mpl-token-metadata/dist/src/hooked/index.js (http://192.168.0.222:3000/static/js/bundle.js:20682:14)
    at options.factory (http://192.168.0.222:3000/static/js/bundle.js:118516:31)

I understand that the problem is in the @metaplex-foundation/mpl-token-metadata library, but I don’t know how to get rid of this error. Here is my code:

import React, {useRef, useState} from 'react';
import { uploadMetadata } from "../../../../action/tokens_api";
import Add from '../../../../assets/images/icons/add.svg'import './styles/styles.css'import { useUmi } from '../../../../components/mint/umi';
import { useSplMinter } from '../../../../components/mint/tokenMinting';

const TokenCreator = () => {    const fileInputRef = useRef(null);
    const [name, setName] = useState('');
    const [symbol, setSymbol] = useState('');
    const [sypply, setSypply] = useState('');
    const [description, setDescription] = useState('');
    const [file, setFile] = useState(null);

    const umi = useUmi('network', 'wallet');
    const splMinter = useSplMinter(umi);

    const handleFileInputClick = () => {
        fileInputRef.current.click();
    };
    const handleFileInputChange = (event) => {
        const file = event.target.files[0];
        setFile(file);
    };
    const handleCreateToken = async () => {
        try {
            const metadataUrl = await uploadMetadata(file, name, description, symbol);
            console.log('Metadata URL:', metadataUrl);
            const mintResult = await splMinter.create({
                name: name,
                symbol: symbol,
                uri: metadataUrl
            }, '3000000000000000000');

            console.log('Mint Result:', mintResult);
        } catch (error) {
            console.error('Error creating token:', error);
        }
    };

    return(
        <div className='creator'>
            form here
        </div>
    )}

export default TokenCreator;
import { createUmi } from '@metaplex-foundation/umi-bundle-defaults';
import { mplTokenMetadata } from '@metaplex-foundation/mpl-token-metadata';
import { walletAdapterIdentity } from '@metaplex-foundation/umi-signer-wallet-adapters';
import API_KEY from'../../action/API_KEY/api_key';

export const useUmi = (network, wallet) => {
    return (
        createUmi(`https://${network}.helius-rpc.com/?api-key=${API_KEY}`)            
            .use(mplTokenMetadata())
            .use(walletAdapterIdentity(wallet))
    );
};
import { percentAmount, generateSigner, createBigInt } from '@metaplex-foundation/umi';
import { fromWeb3JsInstruction } from '@metaplex-foundation/umi-web3js-adapters';
import { ComputeBudgetProgram } from '@solana/web3.js';
import { TokenStandard, createAndMint } from '@metaplex-foundation/mpl-token-metadata';

export const useSplMinter = (umi) => {
    const create = async (metadata = { name: '', symbol: '', uri: '' }, amount = '0') => {
        const mint = generateSigner(umi);
        const priceIx = ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1000000 });

        const transaction = createAndMint(umi, {
            mint,
            authority: umi.identity,
            name: metadata.name,
            symbol: metadata.symbol,
            uri: metadata.uri,
            sellerFeeBasisPoints: percentAmount(0),
            decimals: 9,
            amount: createBigInt(amount),
            tokenOwner: umi.identity.publicKey,
            tokenStandard: TokenStandard.Fungible,
        }).prepend({
            instruction: fromWeb3JsInstruction(priceIx),
            signers: [],
            bytesCreatedOnChain: 0,
        });

        const res = await transaction.sendAndConfirm(umi);

        return { mint: mint.publicKey.toString(), ...res };
    };

    return { create };
};

I would be grateful for any help

DOM is not being uploaded for my Etch-A-Sketch board

Receiving the following error when trying to run the below code: Null value on line 9 due to appendChild. Is my code not reading the etch id?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src ="script.js" defer></script>
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>

    <div id="etch"></div>


    
</body>
</html>
let num = 16;

let etch = document.getElementById("etch");

function board () {
    for(let i = 0; i < num; i++) {
        let row = document.createElement("div");
        row.classList.add("row");
        etch.appendChild(row);

    for(let j = 0; j < num; j++) {
        let column = document.createElement("div");
        column.classList.add("column");
        row.appendChild(column);
      }

    }
 }

 board();

*{
box-sizing: border-box;
margin: 0;
padding: 0;
}

#etch{
    margin: 27px;
    display: flex;
    flex-direction: column;
    width: 500px;
    height: 500px;
    border: black 2px solid;
}

.column{
    display: flex;
    flex-grow: 1;
    background-color: silver;
}

.row{
    flex-grow: 1;
    border: white 1px solid;
}

I am able to get my code to work in MDN playground earlier without adding external js or css files. Not sure what’s going on here. I would appreciate any help. Beginner here.

Javascript Split Array, Split again & Keep Indexes the Same

I have list that I’m trying to split into an array.

The items in the list will not always follow the same pattern. Here’s the example list:

TestOne__Test One|1
TestTwo__Test Two|1
TestThree
TestFour__Test Four
TestFive|1

First I split each item by the ‘__’, which creates the parts array with parts[1] and parts[2] (for any lines that include the __

But, any list items that also contain the “|1” suffix, need to be split as well.

Ideally I will end up with a single parts arrays that looks like this (for each i):

parts = [TestOne, Test One, 1]
parts = [TestTwo, Test Two, 1]
parts = [TestThree]
parts = [TestFour, Test Four]
parts = [TestFive, '', 1]

So the array size/length will depend on each line item.

Here’s the first split:

var promptList = ['TestOne__Test One|1', 'TestTwo__Test Two|1', 'TestThree', 'TestFour__Test Four'];
for (var i = 0; i < promptList.length; i++) {
    var parts = promptList[i].split('__');
}

I have tried splitting all at once with regex:

var parts = promptList[i].split(/['__'|]/);

But that just jumbles up the array indexes. I want all the parts[0] items to be the First part of the line item, and parts[1] to be the second part of the line item (if there is one) and parts[2] to be the ‘1’ suffix (if there is one).

Thanks!

Trying to make multiple divs that are scrolled to certain positions multiple triggers

I’m trying to achieve this but with my limited knowledge and chatgpt couldn’t solve it.

Goal:
Multiple divs that hold long contents that needs to be scrolled, when page is loaded, all divs will be scrolled to certain positions. As all divs have different contents, scrolls are different.

Here’s a sample with Figma
https://www.figma.com/proto/pTRoxhdX3MkT5A5ZHw1WPA/StackOverflow-Question?page-id=0%3A1&type=design&node-id=1-27&viewport=1194%2C529%2C1.2&t=Nb3hRH4d6spTln8C-1&scaling=min-zoom&starting-point-node-id=1%3A26&mode=design

What I have achieved:
I was able to create auto-scrolling with scroll event. Here’s the sample code I created. It has both triggers, one with DOMContentLoaded and one with scroll.

// Function to reset scroll position for a specific scrollable element
function resetScrollPosition(scrollable) {
  const targetItemId = 'current'; 
  
  // Scroll to the target item within the scrollable element
  const targetItem = document.querySelector(`#${targetItemId}`);
  if (targetItem && scrollable.contains(targetItem)) {
    // Scroll to the target item if it's within the scrollable element
    targetItem.scrollIntoView({ behavior: "smooth", block: "center", inline: "nearest" });
  }
}
// Add scroll event listener to each scrollable element
document.addEventListener("DOMContentLoaded", () => {
  const scrollables = document.querySelectorAll('.scrollable');
  const timeouts = {}; // Object to store the timeout for each scrollable element
  
  scrollables.forEach(scrollable => {
    resetScrollPosition(scrollable);
    
    // Add scroll event listener to each scrollable element
    scrollable.addEventListener('scroll', () => {
      // Log a message to the console to check if the scroll event listener is triggered
      
      // Clear the previous timeout for this scrollable element
      clearTimeout(timeouts[scrollable.id]);
      
      // Set a new timeout to reset scroll position after 5 seconds of inactivity
      timeouts[scrollable.id] = setTimeout(() => {
        resetScrollPosition(scrollable);
      }, 1000); // Adjust the timeout duration as needed
    });
  });
});

https://jsfiddle.net/haayany/n45Lbfd2/

However, as you can see in the title of the sample, the it does not move all divs’ scrolls when it’s loaded, but the first div only.

I was able to try it in a slightly different way, and this new one only moves the last one when the page is loaded.

    document.addEventListener("DOMContentLoaded", () => {
        const scrollables = document.querySelectorAll('.scrollable');
        const timeouts = {}; // Object to store the timeout for each scrollable element

        // Function to reset scroll position for a specific scrollable element
        function resetScrollPosition(scrollable) {
            // Replace 'targetItemId' with the ID of the item you want to scroll to
            const targetItemId = 'current';

            // Scroll to the target item within the scrollable element
            const targetItem = scrollable.querySelector(`#${targetItemId}`);
            if (targetItem) {
                // Scroll to the calculated position within the scrollable element
                targetItem.scrollIntoView({ behavior: "smooth", block: "center", inline: "nearest" });
            }
        }

        // Add scroll event listener to each scrollable element
        scrollables.forEach(scrollable => {
            scrollable.addEventListener('scroll', () => {
                // Clear the previous timeout for this scrollable element
                clearTimeout(timeouts[scrollable.id]);

                // Set a new timeout to reset scroll position after 5 seconds of inactivity
                timeouts[scrollable.id] = setTimeout(() => {
                    resetScrollPosition(scrollable);
                }, 5000); // Adjust the timeout duration as needed
            });
        });

        // Call resetScrollPosition for each scrollable element once DOM content is loaded
        scrollables.forEach(scrollable => {
            resetScrollPosition(scrollable);
        });
    });

https://jsfiddle.net/haayany/0tmv4bkw/

I’m not sure how to update this properly to make it happen.