Replace multiple hrefs within menu list with click event

Replace multiple hrefs within menu list with click event,
and load file content into div.

Consider:

<!DOCTYPE html>
<html lang="en">
  <meta charset="utf-8">
  <title>Read file into div</title>
  <article>
    <h1>My HTMl</h1>
    <ul class = "mylist">
      <li><a href="file1.html">Select file 1</a>
      <li><a href="file2.html">Select file 2</a>
      <li><a href="file2.html">Select file 2</a>
    </ul>
    <div id = "SelectedText">
      <h1>Please find selected content below:</h1>
      <p>Replace me
    </div>
  </article>
<!-- Local file -->
<p>file i contains for example:
<h1>Ipsum dolor sit amet</h1>

What I want to achive:

  • Add an event listener to all hrefs in all the lists with class “mylist”.
  • When a file is selected (on click) then replace the content of the div with id=”SelectedText” with the content of the chosen file.

I tried:
<a href="#" onclick="loadDoc('/file1.htm'); return false;">Nieuws</a>
with javascript function:

    <script>
    // Load external HTML document in div.
    function loadDoc(x) {
      .then((result) => {
        if (result.status != 200) { throw new Error("Bad Server Response"); }
        return result.text();
      })
      .then((content) => {
        document.getElementById("content").innerHTML = content;
      })
      .catch((error) => { console.log(error); });
    }
    </script>

But I find a solution with event-handlers more elegant.

Unique Elements in the Array [duplicate]

I have an array, for example nums = [1, 1, 2, 3, 3] on JavaScript;
How can I create an array with unique numbers that do not repeat? Thank you very much for the answer 🙂

const nums = [1, 1, 2, 3, 3];

function uniqueNums(nums) {

};

In my Script it shows “Uncaught TypeError: Cannot read properties of null (reading ‘classList’)” in “div.classList.remove(‘change’)” in this line

I do not find any mistakes here. I tried to check and find the answer several times. Can you please check what my mistake is here?

Here is the HTML

<div class="slideshow"></div>

JS File

// slideshow
const slideshowDivs = () => {
  for (let i = 1; i <= 5; i++) {
    const div = document.createElement("div");
    div.style.backgroundImage = `url(Final/images/slideshow/section-1-bg-${i}.jpg)`;

    i === 1 && div.classList.add("change");

    document.querySelector(".slideshow").appendChild(div);
  }
};

slideshowDivs();

const divs = document.querySelectorAll(".slideshow div");
let a = 1;

const slideshow = () => {
  setInterval(() => {
    a++;

    const div = document.querySelector(".slideshow.change");

    div.classList.remove("change");
    if (a < divs.length) {
      div.nextElementSibling.classList.add("change");
    } else {
      divs[0].classList.add("change");
      a = 1;
    }
  }, 1000);
};
slideshow();
// end of the slideshow

flask api method response.body.getReader() and TextDecorder().decode method are truncating the response received from API

I have an flask API which is returning an HTML table.
sample resp is

{
  "type": "text", 
  "content": "<table border="1" class="dataframe table table-striped">n  <thead>n    <tr style="text-align: right;">n      <th></th>n      <th>Business Group</th>n          <th>Person Type</th>n      <th>Date of Birth</th>n      <th>Hire Date</th>n      <th>Tenure</th>n      <th>Job Name</th>n      <th>Job Level</th>n      <th>HR Business Partner</th>n      <th>Country</th>n      <th>Geo</th>n      <th>Age</th>n      <th>Gender</th>n      <th>Grade Type</th>n     </tr>n  </thead>n  <tbody>n    <tr>n      <th>91</th>n      <td>HR</td>n       <td>Employee</td>n      <td>1973-09-15</td>n      <td>2020-06-09</td>n      <td>4.257534</td>n      <td>Product Designer</td>n      <td>Manager</td>n      <td>Luis Mendez</td>n      <td>United States</td>n      <td>Americas</td>n      <td>51.021918</td>n      <td>Female</td>n      <td>3</td>n     </tr>n  </tbody>n</table>"
}

I am reading this in HTML/JS using the below code block

then(response => {
  const reader = response.body.getReader();
  const decoder = new TextDecoder();
            
  return reader.read().then(function processText({ done, value }) {
    if (done) {
      hideSpinner();
      return;
    }
                
    const chunk = decoder.decode(value, { stream: true });

I am checking the chunk variable it is not giving me proper response. It shows value like this:

{"type": "text", "content": "<table border="1" class="dataframe table table-striped">n  <thead>n    <tr style="text-align: right;">n      <th></th>n      
        <th>Business Group</th>n          <th>Person Type</th>n      <th>Date of Birth</th>n      <th>Hire Date</th>n      <th>Tenure</th>n      <th>Job Name</th>n      <th>Job Level</th>n      <th>HR Business Partner</th>n      <th>Country</th>n      <th>Geo</th>n      <th>Age</th>n      <th>Gender</th>n      <th>Grade Type</th>n     </tr>n  </thead>n  <tbody>n    <tr>n      <th>91</th>n      <td>HR</td>n       <td>Employee</td>n      <td>1973-09-15</td>n      <td>2020-06-09</td>n      <td>4.257534</td>n      <td>Product Designer</td>n      <td>Manager</td>n      <td>Luis Mendez</td>n      <td>United States</td>n      <td>Americas</td>n      <td>51.021918</td>n      <td>Female</td>n      <td>3</td>n

The response is truncated. What can be done to rectify it?

Getting error in importing files in javascript [closed]

node:internal/modules/esm/resolve:265
throw new ERR_MODULE_NOT_FOUND(
^

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/Users/mansavigarg/Coding/Chai_or_Code_BE/BE-Project/src/constants' imported from /Users/mansavigarg/Coding/Chai_or_Code_BE/BE-Project/src/index.js
    at finalizeResolution (node:internal/modules/esm/resolve:265:11)
    at moduleResolve (node:internal/modules/esm/resolve:933:10)
    at defaultResolve (node:internal/modules/esm/resolve:1157:11)
    at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:390:12)
    at ModuleLoader.resolve (node:internal/modules/esm/loader:359:25)
    at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:234:38)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:87:39)
    at link (node:internal/modules/esm/module_job:86:36) {
  code: 'ERR_MODULE_NOT_FOUND',
  url: 'file:///Users/mansavigarg/Coding/Chai_or_Code_BE/BE-Project/src/constants'
}

Getting this error, tried everthing

Tried Chatgpt also, corrected file name to constants to constants.js as well but noting

How would I get about creating this element? [closed]

I have an element with content either side (can’t share because of privacy) and down the middle is a dotted squiggly line. As you scroll up and down the dotted line is covered/uncovered by a solid squiggly line in the same shape (to represent a scroll)

How would I even go about this? I have currently set them both as background images. Am I able to almost crop the solid blue squiggle depending on when I am in terms of scrolling. Is that something this is possible? That’s my main thought.

Any other better ideas are welcome.

Picture of squiggles talked about in post

How to add a tag to a selected text and close/open the parent before/after

trying to create a Richt Texteditor in Javascript. I have a Tag

<span class="text-3xl">Foo</span>

and want to edit it to something like

<span class="text-3xl">F</span><span class="text-sm">o</span><span class="text-3xl">o</span>

My first attempt works, for inserting a Tag inside the other

<span class="text-3xl">F<span class="text-sm">o</span>o</span>

using this code:

  var spanElement= document.createElement("span");
  spanElement.className = size;
  var selection= window.getSelection().getRangeAt(0);
  var selectedText = selection.extractContents();
  elem.appendChild(selectedText);
  selection.insertNode(elem);


but need some help with closing/reopening the tag before/after the inner tag.

Two fingers touch generates touchstart event with a single touch

I’m building a drawing app (JS + HTML canvas) which should handle “pan” gestures.
So I have to distinguish a single-finger-touch (for drawing) and a two-fingers-touch (for panning).
And I’ve noticed that, no matter how fast you put two fingers on a screen, there will always be two touchstart events generated:
the 1st one with a single touch (event.touches.lenght = 1);
and the 2nd one with two touches (event.touches.lenght = 2).

Thus, my log output looks like this:

touchstart -> touches.length = 1 
touchstart -> touches.length = 2 
touchmove -> touches.length = 2 
... 
touchmove -> touches.length = 2 
touchend -> touches.length = 1 
touchend -> touches.length = 0 

This causes a problem – when a user starts panning, the app draws a single dot instead.

The problem described above was reproduced on Android 13 (Chrome v129).
I’ve also tested this with iPadOS 17 in both Safari and Chrome (v110) and discovered that with iPad it’s possible to get the 1st touchstart with two touches in case if you put fingers fast enough and these fingers are not too far from each other.
This makes me guess that it’s a hardware thing related to a fact that a human cannot put two fingers on a screen in exactly the same moment of time.

Eventually, I’ve built a solution that accumulates touchstart and touchmove events, analyzes the sequence and decides whether it was a multi-touch gesture or not.
But still, I’m wondering if there is any standard / easier way to solve this?

Notes:

  • changedTouches don’t help since these let you know what was changed, but not what will be changed;
  • using PointerEvent instead would bring a similar problem since each of the fingers generates its own pointer event.

What am I missing? My function doesn’t work :( [closed]

I’ve made this function named duplicateDiv() that should duplicate a div when clicking on a button.

It looks like this:

function duplicateDiv(divID, parentDiv) {
  let element = document.getElementById(divID);
  let clone = element.cloneNode(true);
  let container = document.getElementById(parentDiv);
  container.appendChild(clone);
}

The button that is being clicked looks like this:

<button
  id="addExerciseFriday"
  class="addExercise"
  onclick="duplicateDiv(programFriday, outerProgramFriday)"
>

The parameters passed into the function on the “onclick” on the button are ID’s of the div I want to copy and the ID of the parent.

Why doesn’t this work?

I’ve had success, but only if I write the function like this:

function duplicateDiv() {
  let element = document.getElementById("programFriday");
  let clone = element.cloneNode(true);
  let container = document.getElementById("outerProgramFriday");
  container.appendChild(clone);

and the button looks like this:

<button
  id="addExerciseFriday"
  class="addExercise"
  onclick="duplicateDiv()"
>

But since I need this function to work on 6 other buttons on my page I don’t want to make several functions to each button. Defeats the purpose of a function, really 😛

Thanks in advance 🙂

I’ve tried many variations to the parameters names, doesn’t work.
I’ve tried changing the document.getElementByID(“divID”) & document.getElementByID(“parentDiv”)

But nothing has worked yet…

While using dnd-kit, is there a way to not have the sortable component re-render in the DragOverlay?

This is my sortable list compon

const [active, setActive] = useState<Active | null>(null);
const activeItem = useMemo(
    () => items.find((item) => item.id === active?.id),
    [active, items],
);

return (
    <DndContext
        modifiers={[restrictToVerticalAxis, restrictToParentElement]}
        sensors={sensors}
        onDragStart={({ active }) => {
            setActive(active);
        }}
        onDragEnd={({ active, over }) => {
            if (over && active.id !== over?.id) {
                const activeIndex = items.findIndex(({ id }) => id === active.id);
                const overIndex = items.findIndex(({ id }) => id === over.id);

                onChange(arrayMove(items, activeIndex, overIndex));
            }
            setActive(null);
        }}
        onDragCancel={() => {
            setActive(null);
        }}
    >
        <SortableContext
            items={itemsWithIds}
            strategy={verticalListSortingStrategy}
        >
            <ul
                role="application"
                className={cn('flex list-none flex-col p-0', gap)}
            >
                {items.map((item, index) => (
                    <React.Fragment key={item.id}>
                        {renderItem(item, index)}
                    </React.Fragment>
                ))}
            </ul>
        </SortableContext>
        <SortableOverlay>
            {activeItem ? renderItem(activeItem) : null}
        </SortableOverlay>
    </DndContext>
);

When I use the sortable overlay (which is a wrapper for DragOverlay), I noticed my component that is rendered flashes, it has some fetch logic in the item, its using react query so it uses the cached data, but it sets it to null for just a second as the item is rendered.
This doesn’t happen when I don’t use DragOverlay as it isn’t creating a copy.

I have a couple ideas of how to solve this but I’m not sure how to do it.
One would be to somehow render the component with its state in one place, and copy it completely with its state, so it doesn’t have to call the hook again to get the data.
Is this something that is possible?

If that’s not possible, is there a way to have drop animations without DragOverlay?

One other idea I had, would it possible to have the item that is dragging not be the newly created one, for example when you drag the item without DragOverlay it doesn’t flash, it only flashes when a new item is created to be dragged, and the the old item is transparent underneath to show where the item will end up.
If it’s possible to swap these two around so that the dragging item is the original component, and the copy is underneath transparent, then the flash wont be a problem.

I’m sure some people will suggest moving the state up, which I’m not sure will be effective using our code base as we use multiple simple API endpoints/hooks, so in these components there will be multiple hooks to get the data, and use caching to make sure performance is ok.

Could not set unknown property ‘classifier’ for task ‘:expo-av:androidSourcesJar’ of type org.gradle.api.tasks.bundling.Jar

ERROR:

A problem occurred evaluating project ':expo-av'.
> Could not set unknown property 'classifier' for task ':expo-av:androidSourcesJar' of type org.gradle.api.tasks.bundling.Jar.

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
> Get more help at https://help.gradle.org.

I’m currently using nx monorepo and pnpm with these i install expo-av i get the above error in my root node_modules

"expo-av": "~14.0.7",

this is how my expo-av is and in my project’s node_modules i have the expo-av like

"expo-av": "~14.0.7",

first i have tried like

"expo-av": "*",

which is also not worked as i expected, kindly help me with this

How to automaticly expand tabulator subtable when a row contains a multi-line cell?

I have a Tabulator table with a subtable. After loading data in the main table, data is loaded to the subtable. Each row in the subtable has some columns which contain data which is loaded asynchronously from the server. After fetching the data, the row.update({...}) function is called which then triggers the cell formatter for that cell. The cell formatter formats the data in 2 rows (inside the cell).
The row height is expanded to fit the contents of the cell, but the table and subtable remain the same height which causes a scrollbar to appear for the subtable.

JSFiddle: https://jsfiddle.net/wk5zcvr4/

I tried calling cell.checkHeight() and cell.getRow().normalizeHeight() using the onRendered parameter of cellFormatter , setting the variableHeight: true option in the columns definition and various css hacks, but none of that worked. When calling cell.getTable().redraw() or cell.getRow().reformat() using the onRendered parameter of cellFormatter it ends up causing an infinite loop.

What I would want is for the subtable to automatically expand itself causing the main table to expand itself. Any help is appreciated

I can’t preview pdfs on the web (mobile device)

I have a floating div in which I have a working PDF preview on the left and a form with the data on the right.

My problem occurs when I want to preview that PDF from a mobile device, the previewer shows the message:

<p>This browser does not support PDFs. Please download the PDF to view it: </p>

and I have preferred that on mobile phones a button be added to open the PDF in another window. and here come my two problems:

  1. the huge space that remains between the button and the form, I don’t know how I can remove it, I have tried to hide the preview and there is still not much space.
  2. the function of the button works almost 100% since it automatically downloads the document, when I only look for it to be previewed, not download it locally.

This is my code:

CSS

<style>
    @media (max-width: 1200px) {
        .preview-container {
            width: 100%;
            height: auto;
            margin-bottom: 20px;
        }

        .row > div {
            flex: 0 0 100%;
            max-width: 100%;
        }

        .file-preview, .embed-container {
            display: none; /* Hide the file preview in small screens */
        }

        .open-btn {
            display: block !important; /* Show the open button in small screens */
        }
    }

    @media (min-width: 1200px) {
        .open-btn {
            display: none !important; /* Hide the open button in large screens */
        }

        .file-preview, .em {
            display: block; /* Show the file preview in large screens */
        }
    }

    .embed-container {
        width: 100%;
        height: 100%;
    }

    .open-btn {
        width: 100%;
        height: 50px;
        margin-top: 10px;
        font-size: 16px;
    }
</style>

HTML and PHP

<div class="modal-body">
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-6 h-600px px-5  preview-container"> <!-- <div class="col-md-6 h-600px px-5 d-none d-xl-block"> -->
                <!-- Container for the Embed  -->
                <?php
                $ext = pathinfo($resultp['name'], PATHINFO_EXTENSION);
                $filePath = '../../../../files' . $resultp['path'] . '/' . $resultp['name'];
                switch ($ext) {
                    case 'pdf':
                        echo '<div class="embed-container file-preview">
                            <object data="' . $filePath . '#toolbar=0" type="application/pdf" width="100%" height="100%">
                                <p>This browser does not support PDFs. Please download the PDF to view it: </p>
                            </object>
                        </div>';
                        echo '<button class="btn btn-primary open-btn" data-url="' . $filePath . '">Open PDF</button>';
                        break;
                        <!--more code-->
            </div>
            <div class="col-md-6 col-12 h-600px px-5"> <!-- <div class="col-md-6"> -->
                <form action="<?= site_url('search/updateFile'); ?>" method="POST" accept-charset="UTF-8" id="updateFile" onsubmit="saveChanges.disabled = true; return true;">
                    <?= csrf_field() ?>
                        <!--form code-->
                </form>
            </div>
        </div>
    </div>
</div>

JavaScript

<script>
    document.addEventListener("DOMContentLoaded", function() {
        const openBtns = document.querySelectorAll('.open-btn');

        openBtns.forEach(btn => {
            btn.addEventListener('click', function() {
                const url = this.getAttribute('data-url');
                const win = window.open(url, '_blank', 'width=800,height=600,scrollbars=yes');
                win.focus();
            });
        });
    });
</script>

This is what the window currently looks like.

Preview Window

I am unable to navigate to other components using onclick() for anchor tag or button

I want the user to be able to click on either of the two links which are rendered in the main component. I do not want to add a new path to the url. The components should be rendered conditionally. Here is my code:-

import React, { useState } from 'react';
import Roadmap1 from './Roadmap1';
import Roadmap2 from './Roadmap2';

const Roadmap = () => {
  const [selectedRoadmap, setSelectedRoadmap] = useState('roadmap1');

  const handleLinkClick = (roadmap) => {
    setSelectedRoadmap(roadmap);
  };

  return (
    <div>
      <div className="navigation-panel">
        <button
          className={`nav-link ${selectedRoadmap === 'roadmap1' ? 'active-link' : ''}`}
          onClick={() => handleLinkClick('roadmap1')}
        >
          First Roadmap
        </button>
        <button
          className={`nav-link ${selectedRoadmap === 'roadmap2' ? 'active-link' : ''}`}
          onClick={() => handleLinkClick('roadmap2')}
        >
          Second Roadmap
        </button>
      </div>

      <div className="roadmap-content">
        {selectedRoadmap === 'roadmap1' && <Roadmap1 />}
        {selectedRoadmap === 'roadmap2' && <Roadmap2 />}
      </div>
    </div>
  );
};

export default Roadmaps;

Despite the above code the links are unclickable nor am I even able to hover over them. However by default the <Roadmap1 /> component is rendered since it is set as the initial value in the useState hook.

Can someone help me understand why my code is experiencing this behaviour?
I went on this link eslint-plugin-jsx-a11y. I switched from anchor tag to button by reading this. Even so i could not make it work.

Web Serial API: “BufferOverrunError” when reading from ESP32 in browser

I’m using the Web Serial API to read data from an ESP32 device via a USB connection, but I consistently encounter the error “BufferOverrunError” in my browser when trying to read data.

Setup:
ESP32 is sending both text and JSON data intermittently.
Baud rate: 19200.
Browser: Chrome (latest version).
I’m using the API to request a port, connect, and continuously read data using read() in a loop.
Problem:
Despite the fact that the ESP32 is not sending large amounts of data (it’s mostly small JSON payloads or text), I keep running into BufferOverrunError on the browser side. I have tried:

Increasing the buffer size (bufferSize) when opening the port.
Adding pauses (setTimeout() or await pauses) to slow down the reading loop.
Processing data in smaller chunks.
None of these approaches have resolved the issue, and I still see the buffer overrun after a short time.

Here is my codes (ESP32 and JS)

ESP32 (Arduino IDE)

void setup() {
  // put your setup code here, to run once:
  Serial.begin(19200);
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println("Hello");
  delay(2000);
}

HTML/JS

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>USB Serial Port Connection</title>
</head>
<body>
    <h1>Connect to USB Serial Port</h1>
    <!-- Button to initiate USB serial connection -->
    <button id="connectButton">Connect to USB</button>
    <!-- Button to disconnect from USB, disabled by default -->
    <button id="disconnectButton" disabled>Disconnect</button>
    <!-- Container to display the data received from the serial port -->
    <pre id="dataOutput"></pre>

    <script>
        let port, reader, isConnected = false;

        // Function to handle connection to the USB serial port
        async function connectSerialPort() {
            try {
                // Request the user to select a serial port (USB) from the available options
                port = await navigator.serial.requestPort();
                
                // Open the selected port with a baud rate of 115200
                await port.open({ baudRate: 19200 });

                // Get a reader to read data from the serial port
                reader = port.readable.getReader();

                // Set the connection status to true
                isConnected = true;
                // Disable the "Connect" button and enable the "Disconnect" button
                document.getElementById('connectButton').disabled = true;
                document.getElementById('disconnectButton').disabled = false;

                // Start reading data from the serial port
                readSerialData();
            } catch (error) {
                // Handle any errors that occur during the connection process
                console.error('Error connecting to the serial port:', error);
            }
        }

        // Function to handle disconnection from the USB serial port
        async function disconnectSerialPort() {
            if (reader) {
                // Cancel and release the reader when disconnecting
                await reader.cancel();
                reader.releaseLock();
            }
            if (port) {
                // Close the port to finish the disconnection process
                await port.close();
            }

            // Reset the connection status to false
            isConnected = false;
            // Re-enable the "Connect" button and disable the "Disconnect" button
            document.getElementById('connectButton').disabled = false;
            document.getElementById('disconnectButton').disabled = true;
        }

        // Function to continuously read data from the serial port
        async function readSerialData() {
            // Create a TextDecoder to convert the raw data into text
            const decoder = new TextDecoder();
            while (isConnected) {
                try {
                    // Read data from the serial port
                    const { value, done } = await reader.read();
                    // Stop reading if there is no more data
                    if (done) break;
                    // If data is received, decode it and append it to the output area
                    if (value) {
                        const decodedData = decoder.decode(value);
                        document.getElementById('dataOutput').textContent += decodedData;
                    }
                } catch (error) {
                    // Handle any errors that occur during data reading
                    console.error('Error reading from the serial port:', error);
                    break;
                }
            }
        }

        // Event listeners for the Connect and Disconnect buttons
        document.getElementById('connectButton').addEventListener('click', connectSerialPort);
        document.getElementById('disconnectButton').addEventListener('click', disconnectSerialPort);
    </script>
</body>
</html>

Questions:
What could be causing this BufferOverrunError on the browser side even with low data throughput?
Are there any strategies or best practices for handling serial data more efficiently using the Web Serial API to avoid buffer overflows?
Could this be related to how Chrome or the Web Serial API handles buffers, or is it something on the ESP32 side?
Any insights or suggestions would be greatly appreciated!