Use previously cached selectors with querySelector()

How can I use previously cached selectors with certain aspects of querySelector() ?

For example, I have this HTML / JavaScript:

let L1, L2, L3;
L1 = document.querySelector('#L1');

L2 = L1.querySelector('div:nth-child(1)');
L2.classList.add('L2');

L3 = L1.querySelector('div:nth-child(2)');
L3.classList.add('L3');

console.log(L2);
console.log(L3);
<div id="L1">
  <div id="L2">
    <div id="L2a"></div>
    <div id="L2b"></div>
  </div>
  <div id="L3"></div>
</div>
Notice that div#L2b gets the className ‘L3’ instead of div#L3 getting it.

What I really want to do is something like:

L3 = L1.querySelector('> div:nth-child(2)');

to force querySelector() to choose the correct nth-child(2). For example, as in this demo that does NOT cache the selectors:

let L1, L2, L3;
const $ = document.querySelector.bind(document);
L1 = document.querySelector('#L1');

L2 = L1.querySelector('div:nth-child(1)');
L2.classList.add('L2');

L3 = document.querySelector('div#L1 > div:nth-child(2)');
L3.classList.add('L3');

console.log(L2);
console.log(L3);
<div id="L1">
  <div id="L2">
    <div id="L2a"></div>
    <div id="L2b"></div>
  </div>
  <div id="L3"></div>
</div>

Is there any way this can be done with the L1 cached selector?

In my real-world use case, the L1 selector looks more like:

const $ = document.querySelector.bind(document);
$('body > div > div#main > div:nth-child(3) > div:nth-child(1) > div > div#L1');

I cringe at typing that string before each of 15 selectors I must cache.

How can i align the rows of a div with contenteditable with the numbers of a vertical column with div and span, using Highlightjs library?

I would like to align the rows of text with the numbers in the yellow vertical bar. As you can see from the image, the problem is that the first and second lines are not well aligned with the numbers in the yellow column. The rows in the black panel are created in the yellow empty spaces between the numbers.


enter image description here

I would have liked not to use the Highlightjs library (to select the text color) in the question code, but i noticed that using Highlightjs adds css that creates additional empty space. Without Highlightjs i have the same problem, but with Highlightjs the empty space is greater, so to find the solution you have to use Highlightjs which already i inserted in html as tag and cdn:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/vs2015.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>

Below you will find the working snippet where everything is included.

In .numbers css, i managed the vertical space between the numbers with the line-height: 1.3 and also their size with font-size: 16px, so i would like the space and size to remain the same.

How can i align the lines to the numbers correctly? I tried changing some paddings or margins, but doing so breaks the mouse pointer after the last letter of a word or breaks in other ways. I would like to get this or something very similar:

enter image description here

IMPORTANT: Pay attention to the broken mouse pointer on the rows, because the line alignment problem seems solved, but the pointer breaks and does not flash correctly on the rows

In case of help, please please use my code for the solution and not another example code, because as you can see my code is a bit peculiar. Thank you

/// CODE ROWS ///
const textarea = document.querySelector(".hilite-editor");
const numbers = document.querySelector(".numbers");

function updateLineNumbers() {
  const num = textarea.innerHTML.split("n").length;
  numbers.innerHTML = Array(num).fill("<span></span>").join("");
}

// Update line numbers when the page loads
updateLineNumbers();

// Update line numbers when the textarea content changes
textarea.addEventListener("input", updateLineNumbers);

// WHEN I PRESS KEY
textarea.addEventListener("keydown", (event) => {
  if (event.key === "Tab") {
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;

    textarea.innerHTML =
      textarea.innerHTML.substring(0, start) +
      "t" +
      textarea.innerHTML.substring(end);

    event.preventDefault();
  }
});

/// CODE EDITOR ///

const elHTML = document.querySelector(`[data-lang="html"]`);
const elCSS = document.querySelector(`[data-lang="css"]`);
const elJS = document.querySelector(`[data-lang="js"]`);
const elPreview = document.querySelector("#preview");

const hilite = (el) => {
  const elCode = el.previousElementSibling.querySelector("code");
  elCode.textContent = el.textContent;
  delete elCode.dataset.highlighted;
  hljs.highlightElement(elCode);
};

const preview = () => {  
  const encodedCSS = encodeURIComponent(`<style>${elCSS.textContent}</style>`);
  const encodedHTML = encodeURIComponent(elHTML.textContent);
  const encodedJS = encodeURIComponent(`<scr` + `ipt>${elJS.textContent}</scr` + `ipt>`); 
  const dataURL = `data:text/html;charset=utf-8,${encodedCSS + encodedHTML + encodedJS}`;
  elPreview.src = dataURL;
};

// Initialize!

[elHTML, elCSS, elJS].forEach((el) => {
  el.addEventListener("input", () => {
    hilite(el);
    preview();
  });
  hilite(el);
});

preview();
/******** CODE EDITOR HIGHTLIGHTS.JS **********/  
/* Scrollbars */
::-webkit-scrollbar {
  width: 5px;
  height: 5px;
}

::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 0px;
}

::-webkit-scrollbar-thumb {
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 1rem;
}


.hilite {
position: relative;
background: #1e1e1e;
height: 120px;
overflow: auto;
width: 100%;
height: 100%;
}

.hilite-colors code,
.hilite-editor {
padding: 1rem !important;
top: 0;
left: 0;
right: 0;
bottom: 0;
white-space: pre-wrap;
font: 13px/1.4 monospace;
width: 100%;
background: transparent;
border: 0;
outline: 0;
}

/* THE OVERLAYING CONTENTEDITABLE WITH TRANSPARENT TEXT */
.hilite-editor {
display: inline-block;
position: relative;
color: transparent; /* Make text invisible */
caret-color: hsl( 50, 75%, 70%); /* But keep caret visible */
width: 100%;
}
.hilite-editor:focus {
outline: transparent;
}
.hilite-editor::selection {
background: hsla(0, 100%, 75%, 0.2);
}

/* THE UNDERLAYING DIV WITH HIGHLIGHT COLORS */
.hilite-colors {
position: absolute;
user-select: none;
width: 100%;
}

#preview {
display: block;
background: #fff;
width: 100%;
height: 100%;
border: 0;
}

/* highlight.js customizations: */
.hljs {
background: none;
}


#preview.resizing {
  pointer-events: none;
}

/******** COUNT ROWS **********/  
.numbers {
 text-align: right;
 background: yellow;
 /* padding-right: 20px; */
 width: 35px;
 height: 200px;
 /* margin-right: 71px; */
 line-height: 1.3;
 font-size: 15px;
}

.numbers span {
 counter-increment: linenumber;
}

.numbers span::before {
 content: counter(linenumber);
 display: block;
 color: black;
}

/******** CONTAINERS **********/  
.container {
 /*max-width: 700px; */
 min-height: 16em;
 border-radius: 4px;
 margin: 0;
 padding:0;
}

.container--tabs {
 list-style: none;
 display: flex;
 flex-direction: row;
 justify-content: flex-start;
 align-items: stretch;
 margin: 0;
 padding:0;
 background-color: #282828;

 .tab {
   min-height: 2em;
   padding: 7px;
   box-sizing: border-box;
   width: 127px;
   text-align: center;
   cursor: pointer;
   background-color: #363636;
   color: white;
   transition: background-color 0.25s;
   border-right: 1px solid #5a5a5a;

   &:hover {
     background-color: rgba(0, 0, 0, 0.25);
     transition: background-color 0.25s;
     color: white;
   }
 }

 .tabs--active {
   background-color: #1e1e1e;
   color: white;
   pointer-events: none;
 }
}

.content {
 display: none;
 padding: 0;

}

.content--active {
 display: flex;
 height: 800px;
}

h1 {
 margin-bottom: 0.5em;
 font-weight: 700;
}

p {
 font-weight: 300;
}
<!-- Highlight js -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/vs2015.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>

    <!-- Bootstrap -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://getbootstrap.com/docs/5.3/assets/css/docs.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

<div class="container--content">
  <div class="content content--active">

    <div class="numbers">
      <span></span>
    </div>  

    <div class="hilite">

      <pre class="hilite-colors"><code class="language-html"></code></pre>
      <div
           data-lang="html"
           class="hilite-editor"
           contenteditable="true"
           spellcheck="false"
           autocorrect="off"
           autocapitalize="off"
           >&lt;h1 class="heading" title="test this" data-some='foo bar'>This is a Heading&lt;/h1>   
        &lt;p>This is a paragraph.&lt;/p></div>
    </div>  
  </div>
  
  
</div>
</div>

Error [ERR_UNHANDLED_ERROR]: Unhandled error. (undefined)

So I was working on a multiplayer survival type game, and at some point I had 3 message component collectors nested within each other, which lead to the inner most collector just failing. So instead I set it so there is a promise which gets resolved when the outermost collector ends, and I await that, once the promise is resolved we move to creating the next collector and the inner collector, but then it gives an error which was undefined. That without ever going past the promise. Normally I can fix my own errors, but this has thoroughly stumped me.
This is the command which was the multiplayer survival game I was talking about.
https://sourceb.in/ebtBGKmQWQ
error screenschot

SO I had multiple trycatch blocks, the first being the one in the command file. Second was in interactionCreate event.

try {
    await command.execute(interaction, client);
} catch (error) {
    console.log(
        `[INTERACTION CREATE] ${error.stack}n[INTERACTION CREATE] ${
            interaction.user.username
        } used ${interaction.commandName} in ${interaction.channel.name} at ${new Date(
            Date.now()
        )}`.red
    );
    return await interaction
        .reply({
            content: "There was an error while executing this command!",
            ephemeral: true,
        })
        .catch((e) => {});
}

Above even that was another trycatch block

try {
    //other things
    //the previous trycatch block
} catch (error) {
    console.log(`[INTERACTION CREATE] ${error.stack}n${new Date(Date.now())}`.red);
}

Then in my index.js I had these:

process.on("unhandledRejection", (reason, promise) => {
    console.log(
        `[BOT] Unhandled Rejection at ${promise}n[BOT] Unhandled Rejection reason: ${
            reason.stack
        }n${new Date(Date.now())}`.red
    );
});

process.on("uncaughtException", (error, origin) => {
    console.log(
        `[BOT] Uncaught Exception at ${origin}n[BOT] Uncaught Exception error: ${
            error.stack
        }n${new Date(Date.now())}`.red
    );
});

process.on("uncaughtExceptionMonitor", (error, origin) => {
    console.log(
        `[BOT] Uncaught Exception Monitor at ${origin}n[BOT] Uncaught Exception Monitor error: ${
            error.stack
        }n${new Date(Date.now())}`.red
    );
});

I also had an error event which console logs the error.stack. But everything kept saying TypeError: Cannot read properties of undefined (reading ‘stack’)
so I put all those in comments and the resulting error is the image included.
As I said, normally I can fix my own mess, but I don’t even know where to begin with this.

Store data into a JSON file (electron app)

I am trying to store my data from variables apiKey and steam64id into a JSON file.

const {icpRenderer, clipboard} = require("electron")
const fs = require("fs")
const path = require("path")

var localappdata
var config

if (process.platform == "win32") {
    localappdata = path.join(process.env.LOCALAPPDATA)
}

config = path.join(localappdata, "Achievement Notifier", "config.json");

var apiKey = "apikey"
var steam64id = "steam64id"

json file:

{"apiKey":"","steam64id":""}

I am unsure on how to store the data into the JSON file. I have tried using fs.writeFileSync but it didnt update the json file.

How to keep RadixUI Tooltip/Modal in dom

I’m using RadixUI library (https://www.radix-ui.com/primitives/docs/components/tooltip) for my components. The problem is that I’d like to keep the content of my Tooltip in dom. Currently, it appears only on hover and is rendered in body element as a last child. What I’d like to obtain is that:

  1. Tooltip content is always kept in dom (for example with display: none style)
  2. Tooltip content is rendered inside my tooltip trigger or at least in a way that its possible to identify with which trigger its associated

Simple To-Do List Application [closed]

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body {
            background-color: #994d00;
            font-family: 'Helvetica', sans-serif;
        }

        #panel {
            background-color: #ff901a;
            width: 50%;
            margin: auto;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.3);
        }

        #form {
            margin-bottom: 20px;
        }

        input[type="text"] {
            width: 70%;
            padding: 10px;
            border: none;
            border-radius: 5px;
        }
        h1 {
            color: white;
            text-shadow: 0 0 10px rgba(0, 0, 0, .8);
           }
        button {
            background-color: #994d00;
            color: white;
            border: none;
            padding: 10px;
            border-radius: 5px;
            cursor: pointer;
        }

        ul {
            list-style: none;
            padding: 0;
        }

        li {
            background-color: white;
            margin-bottom: 10px;
            padding: 10px;
            border-radius: 5px;
            border: 2px solid #994d00;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .delete-btn {
            background-color: #994d00;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 3px;
            cursor: pointer;
        }
    </style>
  <title>Lista Zadań</title>
</head>
<body>

<div id="panel">
    <h1>Rzeczy do zrobienia</h1>
    <ul id="taskList"></ul>
    <form id="form">
        <input type="text" id="taskInput" placeholder="Dodaj nowe zadanie" required>
        <button type="button" onclick="dodajZadanie()">Dodaj</button>
    </form>
</div>

<script>
    function dodajZadanie() {
        var taskInput = document.getElementById("taskInput");
        var taskList = document.getElementById("taskList");

        if (taskInput.value.trim() !== "") {
            var newTask = document.createElement("li");
            newTask.innerHTML = taskInput.value + '<button class="delete-btn" onclick="usunZadanie(this)">Usuń</button>';
            taskList.appendChild(newTask);
            taskInput.value = "";
        }
    }

    function usunZadanie(btn) {
        var listItem = btn.parentNode;
        listItem.parentNode.removeChild(listItem);
    }
</script>
</body>
</html>

brief description of the code:

This code creates a simple to-do list application. It has a header that says “Rzeczy do zrobienia” (Things to do), a list of tasks, and a form to add new tasks. The form has a text input field for entering the task description and a button to submit the task. When the submit button is clicked, the function dodajZadanie() is called, which creates a new list item with the task description and a delete button. The new list item is then appended to the task list. The delete button has a click event listener that calls the function usunZadanie(), which removes the list item that contains the button.

What happens when a task is deleted from the list?
How does the code ensure that only valid tasks can be added to the list?

JS newbie: NodeList returns null but has elements

I had working Javascript/HTML code when it was all in one file and now I want to split it into separate files.

My JS code was working before the split, but when I moved it to a new file, the commented out portion stopped working. I’m self-taught, so this might be something obvious but I haven’t come across the right info yet. I can’t access the element and I’m not sure why. How can I fix it? And: Is there some place that discusses why it worked in the same file but separating the code would break it like that? Thanks for any insight!

Before the move, my JS code was at the bottom of my HTML and I’ve seen that that sometimes makes a difference. I tried the <script src> at the bottom, but no difference.

My relevant HTML code block:

{%- block scripts %}
  <script src="{{ url_for('static',filename='download_page.js') }}"></script>
{%- endblock scripts %}
{% block title %} Download Page {% endblock title %}
{% block page_heading %} Download Shelf Tool{% endblock page_heading %}
{% block content -%}
{# #}
    <form action="{{ url_for('download_shelf_func') }}" method="post" name="choice_form">
      {{ form.csrf_token }}
      <form-title>
        {{ form.form_name.label(class="form-title") }}
      </form-title>
      <form-row>
        {{ form.shelf_choice.label(class="item-label") }}
        {{ form.shelf_choice(class="drop-down-menu", onchange="setShelfChoice(this)") }}
      </form-row>

Tried it without this but no change.

My JS code:

document.addEventListener('DOMContentLoaded', setShelfChoice());

function setShelfChoice() { 
  let el = document.getElementsByName('shelf_choice');
  console.log("el type: ", typeof(el), el);
  console.log("el value: ", el[0].value);
  // let index = el.selectedIndex;
  // choiceValue = el.options[index].textContent;
  // console.log("setShelfChoice: ", choiceValue, "nn");
  // console.log("index: ", index);
}

When I reload the HTML page, it calls the function, and there is a Node 0 in the array and it has all the right values. But I’m not sure what I should be calling if not [0].

I tried changing console.log("el: ", el[0].value); to console.log("el: ", el[0]); the output just says undefined.

I tried adding an initialization but that hasn’t affected anything:

function setShelfChoice() { 
  let el = document.getElementsByName('shelf_choice');
  if (el.selectedIndex == undefined) {
    el.selectedIndex = 0;
  }
  console.log("el: ", typeof(el), el);
  console.log("el: ", el.value);

console output

Unable to Apply ‘key’ Prop to React Component Within a Mapped Array

enter image description hereI am encountering difficulties applying the key prop to a React component within a mapped array in a Next.js application. The code snippet involves a Slider component and a mapped array of Image components. Despite providing a unique key for each element within the .map() function, the React application does not recognize the key prop, and I’m experiencing unexpected behavior.

"use client";

import Image from "next/image";
import React from "react";
import Slider from "react-slick";
import mediaPlaceHolder from "@public/assets/icons/mediaplaceholder.png";

export default function NetworkSlider({ data }) {
  const settings = {
    dots: false,
    infinite: false,
    speed: 500,
    slidesToShow: 7,
    slidesToScroll: 7,
    initialSlide: 0,
  };

  return (
    <section>
      <Slider {...settings}>
        {data
          .sort((a, b) => {
            return a.display_priority - b.display_priority;
          })
          .slice(0, 21)
          .map((network) => (
            <div key={network.id} className="flex justify-center">
              <Image
                src={
                  network.logo_path !== null
                    ? `http://image.tmdb.org/t/p/original${network.logo_path}`
                    : mediaPlaceHolder
                }
                width={"300"}
                height={"500"}
                className=" rounded-lg h-auto w-auto"
                alt={`Logo of ${network.provider_name} `}
                priority={true}
              />
            </div>
          ))}
      </Slider>
    </section>
  );
}

Speed Inconsistencies in Browser “Go Back” Function Across Chrome, Edge, and Firefox

I’m encountering a noticeable speed inconsistency with the “Go Back” function in multiple browsers (specifically Chrome, Edge, and Firefox). This issue seems to be related to the speed at which the function operates, rather than its ability to navigate to the correct previous page.

Example Scenario:

A typical example of this issue is observed on YouTube. When I click to go back to a previously watched video, I find that manually searching for the video and clicking on it is consistently faster than using the “Go Back” function.

Question:

  1. What could be causing the slower response time of the “Go Back”
    function in these browsers, especially on dynamic sites like
    YouTube?
  2. Are there differences in how these browsers handle caching or
    history states that might contribute to this lag or is there a universal approach?
  3. Is the slower performance related to how browsers process dynamic
    content, JavaScript, or AJAX on sites like YouTube?

I’m seeking a technical explanation to understand why there is a disparity in the speed of the “Go Back” function across different browsers, particularly in the context of modern, dynamic websites.

Having trouble with sending data from JavaScript to Python Flask

I am running a simple setup where a string should be sent to my Flask app via Ajax, but I am receiving Error code 400: Bad request.

JavaScript code:

headers = {
    'Content-type':'application/json',
    'Accept':'application/json'
}

function send(){
    const line = textbox.value;
    $.ajax({
        type: "POST",
        url: "/send",
        data: line,
        headers: headers,
    });
}

Python code:

@app.route("/send", methods=["POST"])
def print_data():
    data = json.load(request.get_json().get("data"))
    main.FileMan.post_data(str(data))

Where the last line is where I call a Python file called main and output the data in a text document.

CSS/JS: Problem aligning the rows of a div with contenteditable with the numbers of a vertical column with div and span

I would like to align the rows of text with the numbers in the yellow vertical bar. As you can see from the image, the problem is that the first and second lines are not well aligned with the numbers in the yellow column. The rows in the black panel are created in the yellow empty spaces between the numbers.

enter image description here

In .numbers css, i managed the vertical space between the numbers with the line-height: 1.3 and also their size with font-size: 16px, so i would like the space and size to remain the same.

How can i align the lines to the numbers correctly? I tried changing some paddings, but doing so breaks the mouse pointer after the last letter of a word. I would like to get this or something very similar:

enter image description here

In case of help, please please use my code for the solution and not another example code, because as you can see my code is a bit peculiar. Thank you

const textarea = document.querySelector(".hilite-editor");
const numbers = document.querySelector(".numbers");

function updateLineNumbers() {
  const num = textarea.innerHTML.split("n").length;
  numbers.innerHTML = Array(num).fill("<span></span>").join("");
}

// Update line numbers when the page loads
updateLineNumbers();

// Update line numbers when the textarea content changes
textarea.addEventListener("input", updateLineNumbers);

// WHEN I PRESS KEY
textarea.addEventListener("keydown", (event) => {
  if (event.key === "Tab") {
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;

    textarea.innerHTML =
      textarea.innerHTML.substring(0, start) +
      "t" +
      textarea.innerHTML.substring(end);

    event.preventDefault();
  }
});

/////////////////////////////////////////////////////////

const elHTML = document.querySelector(`[data-lang="html"]`);
const elCSS = document.querySelector(`[data-lang="css"]`);
const elJS = document.querySelector(`[data-lang="js"]`);
const elPreview = document.querySelector("#preview");

const hilite = (el) => {
  const elCode = el.previousElementSibling.querySelector("code");
  elCode.textContent = el.textContent;
  delete elCode.dataset.highlighted;
  hljs.highlightElement(elCode);
};

const preview = () => {  
  const encodedCSS = encodeURIComponent(`<style>${elCSS.textContent}</style>`);
  const encodedHTML = encodeURIComponent(elHTML.textContent);
  const encodedJS = encodeURIComponent(`<scr` + `ipt>${elJS.textContent}</scr` + `ipt>`); 
  const dataURL = `data:text/html;charset=utf-8,${encodedCSS + encodedHTML + encodedJS}`;
  elPreview.src = dataURL;
};

// Initialize!

[elHTML, elCSS, elJS].forEach((el) => {
  el.addEventListener("input", () => {
    hilite(el);
    preview();
  });
  hilite(el);
});

preview();
/********* EDITOR CODE ***********/
.hilite {
position: relative;
background: #1e1e1e;
height: 120px;
overflow: auto;
width: 100%;
height: 100%;
}

.hilite-colors code,
.hilite-editor {
padding: 1rem !important;
top: 0;
left: 0;
right: 0;
bottom: 0;
white-space: pre-wrap;
font: 13px/1.4 monospace;
width: 100%;
background: transparent;
border: 0;
outline: 0;
}

/* THE OVERLAYING CONTENTEDITABLE WITH TRANSPARENT TEXT */
.hilite-editor {
display: inline-block;
position: relative;
color: transparent; /* Make text invisible */
caret-color: hsl( 50, 75%, 70%); /* But keep caret visible */
width: 100%;
}
.hilite-editor:focus {
outline: transparent;
}
.hilite-editor::selection {
background: hsla(0, 100%, 75%, 0.2);
}

/* THE UNDERLAYING DIV WITH HIGHLIGHT COLORS */
.hilite-colors {
position: absolute;
user-select: none;
width: 100%;
}

/* highlight.js customizations: */
.hljs {
background: none;
}
/* End Editor Code */

/******** COUNT ROWS **********/  

.numbers {
 text-align: right;
 background: yellow;
 /* padding-right: 20px; */
 width: 35px;
 height: 200px;
 /* margin-right: 71px; */
 line-height: 1.3;
 font-size: 16px;
}

.numbers span {
 counter-increment: linenumber;
}

.numbers span::before {
 content: counter(linenumber);
 display: block;
 color: black;
}


/* End Count Row */  


/******** CONTAINERS EDITOR CODE **********/  
.content {
 display: none;
 padding: 0;
}

/* Tabs, Tabcontrol */  
.content--active {
 display: flex;
 height: 800px;
}

body {
  color: white;
}
/* End Containers Editor Code */  
<div class="container--content">
  <div class="content content--active">


    <div class="numbers">
      <span></span>
    </div>  

    <div class="hilite">

      <pre class="hilite-colors"><code class="language-html"></code></pre>
      <div
           data-lang="html"
           class="hilite-editor"
           contenteditable="true"
           spellcheck="false"
           autocorrect="off"
           autocapitalize="off"
           >&lt;h1 class="heading" title="test this" data-some='foo bar'>This is a Heading&lt;/h1>   
        &lt;p>This is a paragraph.&lt;/p></div>
    </div>  
  </div>
  
  
</div>
</div>

no Info Window for markers

From external file:

const pos=[
[50.739,7.0894,0,9,0],
[50.839,7.1894,10,10,100],
[50.939,7.2894,10,11,50]
];

This is my code:

<script>
  function initMap() {
  const map = new google.maps.Map(document.getElementById("map"),{zoom:8,center:{lat:50.667921396523546,lng:7.150112452250704}});

  //Start
  const infowindow = new google.maps.InfoWindow({content:"Start",ariaLabel:"Start"});
  const marker = new google.maps.Marker({position:{lat:50.667921396523546,lng:7.150112452250704},map,title:"Start"});
  marker.addListener("click", () => {infowindow.open({anchor:marker,map});});

  infowindowA = new Array;
  markerA = new Array;
  for (i=0;i<pos.length;i++){
  //infowindowA[i] = new google.maps.InfoWindow({content:"Pos",ariaLabel:"Pos"});
  infowindowA[i] = new google.maps.InfoWindow({content:"Pos "+(i+1)+"<br>Zeit "+pos[i][3]+"<br>akt. Geschwindigkeit "+pos[i][4]+"km/h<br>Distanz zu Pos"+i+" "+pos[i][2]+"km",ariaLabel:"Pos"+(i+1)}); 
  markerA[i] = new google.maps.Marker({position:{lat:pos[i][0],lng:pos[i][1]},map,title: "Pos"+(i+1)});
  markerA[i].addListener("click", () => {infowindowA[i].open({anchor:markerA[i],map});});
  }

  //Ziel
  const infowindowz = new google.maps.InfoWindow({content:"Ziel",ariaLabel:"Ziel"});
  const markerz = new google.maps.Marker({position:{lat:50.039600,lng:8.530919},map,title: "Animal Lounge"});
  markerz.addListener("click", () => {infowindowz.open({anchor:markerz,map});});
}
window.initMap = initMap;
</script>

InfoWindow only appears for Start and Ziel, but not for markers in the loop.

These two lines in the for loop may have an error:

infowindowA[i] = new google.maps.InfoWindow({content:"Pos "+(i+1)+"<br>Zeit "+pos[i][3]+"<br>akt. Geschwindigkeit "+pos[i][4]+"km/h<br>Distanz zu Pos"+i+" "+pos[i][2]+"km",ariaLabel:"Pos"+(i+1)}); 
markerA[i].addListener("click", () => {infowindowA[i].open({anchor:markerA[i],map});});

because this line works

markerA[i] = new google.maps.Marker({position:{lat:pos[i][0],lng:pos[i][1]},map,title: "Pos"+(i+1)});

I tried to check the content:

alert("Pos "+(i+1)+"<br>Zeit "+pos[i][3]+"<br>akt. Geschwindigkeit "+pos[i][4]+"km/h<br>Distanz zu Pos"+i+" "+pos[i][2]+"km");

but works fine.

Im trying to create an app, a social media app. Im struggling to undarstand how to develop on back end [closed]

Seeking Collaboration for Front-End and Back-End Integration

Hello, amazing community!

I’m currently working on an exciting social network project called ABOA, and I’m looking for talented individuals who can lend their expertise in integrating the front-end and back-end components. ABOA aims to connect people for unforgettable experiences, and your help can make it even more incredible!

What We Need Help With: We’re at a crucial stage where we need assistance in seamlessly bringing together the front-end design and the back-end functionality. If you have experience in web development, particularly with front-end technologies like HTML, CSS, and JavaScript, as well as back-end technologies such as Python or Node.js, your skills would be invaluable.

How You Can Contribute:

  • Collaborate on designing and implementing an interactive user interface.

  • Assist in connecting the front-end to the back-end functionalities.

  • Optimize and enhance user experience across different devices.

Why Contribute: By contributing to ABOA, you’ll be part of creating a platform that fosters unforgettable social experiences. It’s an opportunity to showcase your skills, collaborate with a passionate team, and make a positive impact on the way people connect and share moments.

How to Get Involved: Feel free to reach out if you’re interested or have any questions. You can reach at at [email protected]. Your expertise is highly valued, and together, we can bring ABOA to new heights!

Thank you for considering joining this exciting journey!

Best regards, José

import sqlite3
import os

connection = None  # ou substitua por um objeto de conexão real, dependendo do seu código

def criar_tabela():
    caminho_diretorio = 'C:\Users\ejose\OneDrive\Documentos\Projetos Marolentos\templates'
    caminho_banco_dados = os.path.join(caminho_diretorio, 'avaliacoes.db')
    conn = sqlite3.connect(caminho_banco_dados)
    cursor = conn.cursor()

    cursor.execute('''
        CREATE TABLE IF NOT EXISTS avaliacoes (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            usuario TEXT,
            festa TEXT,
            avaliacao INTEGER,
            comentario TEXT
        )
    ''')

    conn.commit()
    conn.close()

def adicionar_avaliacao(usuario, festa, avaliacao, comentario):
    caminho_diretorio = 'C:\Users\ejose\OneDrive\Documentos\Projetos Marolentos\templates'
    caminho_banco_dados = os.path.join(caminho_diretorio, 'avaliacoes.db')
    conn = sqlite3.connect(caminho_banco_dados)
    cursor = conn.cursor()

    cursor.execute('''
        INSERT INTO avaliacoes (usuario, festa, avaliacao, comentario)
        VALUES (?, ?, ?, ?)
    ''', (usuario, festa, avaliacao, comentario))

    cursor.execute("INSERT INTO avaliacoes (usuario, festa, avaliacao, comentario) VALUES (?, ?, ?, ?)",
                   (usuario, festa, avaliacao, comentario))
    try:
        connection.commit()
    except AttributeError as e:
        print(f"Erro ao tentar commit: {e}")

    conn.commit()
    conn.close()


def obter_avaliacoes():
    caminho_diretorio = 'C:\Users\ejose\OneDrive\Documentos\Projetos Marolentos\templates'
    caminho_banco_dados = os.path.join(caminho_diretorio, 'avaliacoes.db')
    conn = sqlite3.connect(caminho_banco_dados)
    cursor = conn.cursor()

    cursor.execute('SELECT * FROM avaliacoes')
    avaliacoes = cursor.fetchall()

    try:
        connection.commit()
    except AttributeError as e:
        print(f"Erro ao tentar commit: {e}")


    conn.close()

    return avaliacoes

# Exemplo de uso
criar_tabela()


adicionar_avaliacao('João', 'Festa Legal', 4, 'Gostei bastante!')
adicionar_avaliacao('Maria', 'Evento Top', 5, 'Incrível!')

avaliacoes = obter_avaliacoes()
print(avaliacoes)

adicionar_avaliacao('João', 'Festa Legal', 4, 'Gostei bastante!')
adicionar_avaliacao('Maria', 'Evento Top', 5, 'Incrível!')

avaliacoes = obter_avaliacoes()
print(avaliacoes)

...............................................................

from flask import Flask, render_template, request, jsonify
import sqlite3

app = Flask(__name__)

# Configuração do SQLite
DATABASE = 'database.db'

def create_table():
    connection = sqlite3.connect(DATABASE)
    cursor = connection.cursor()
    cursor.execute('''CREATE TABLE IF NOT EXISTS avaliacao (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        usuario TEXT NOT NULL,
                        festa TEXT NOT NULL,
                        avaliacao INTEGER NOT NULL,
                        comentario TEXT NOT NULL
                    )''')
    connection.commit()
    connection.close()

@app.route('/')
def index():
    create_table()
    return render_template('avaliacao.html')

@app.route('/api/adicionar_avaliacao', methods=['POST'])
def adicionar_avaliacao():
    data = request.get_json()
    usuario = data['usuario']
    festa = data['festa']
    avaliacao = data['avaliacao']
    comentario = data['comentario']

    connection = sqlite3.connect(DATABASE)
    cursor = connection.cursor()
    cursor.execute('''INSERT INTO avaliacoes (usuario, festa, avaliacao, comentario) 
                       VALUES (?, ?, ?, ?)''', (usuario, festa, avaliacao, comentario))
    connection.commit()
    connection.close()

    return jsonify({"message": "Avaliação adicionada com sucesso!"})

@app.route('/api/listar_avaliacoes')
def listar_avaliacoes():
    connection = sqlite3.connect(DATABASE)
    cursor = connection.cursor()
    cursor.execute('''SELECT * FROM avaliacoes''')
    avaliacoes = cursor.fetchall()
    connection.close()

    return jsonify({"avaliacoes": avaliacoes})

if __name__ == '__main__':
    app.run(debug=True)

...................................................

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ABOA App - Avaliações</title>
    <link rel="stylesheet" href="MAROLEX.css"/>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-wtGA6z8A3nh1h9OPI8XU4e0YNbFddA/SwPPznU0Js1zsvugNqumZD3F6ExB5X7j3giF0AZzUnViI/Vd31ZI6foA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
<body>

    <header>
        <h1>ABOA App - Avaliações</h1>
        <p>Conectando pessoas para experiências inesquecíveis!</p>
    </header>

    <nav>
        <ul>
            <li><button onclick="navigateTo('index.html')">Home</button></li>
            <li><button onclick="navigateTo('sobre-nos.html')">Sobre Nós</button></li>
            <li><button onclick="navigateTo('contato.html')">Contato</button></li>
            <li><button onclick="navigateTo('avaliacao.html')">Avaliação</button></li>
            <li><button onclick="navigateTo('compartilhamento.html')">Compartilhamento</button></li>
            <li><button onclick="navigateTo('social.html')">Social</button></li>
        </ul>
    </nav>

    <main>
        <!-- Formulário para Adicionar Avaliação -->
        <section>
            <h2>Adicionar Avaliação</h2>
            <form onsubmit="adicionarAvaliacao(event)">
                <label for="usuario">Usuário:</label>
                <input type="
                <input type="text" id="usuario" name="usuario" required>

                <label for="festa">Festa:</label>
                <input type="text" id="festa" name="festa" required>

                <label for="avaliacao">Avaliação:</label>
                <select id="avaliacao" name="avaliacao" required>
                    <option value="1">1 estrela</option>
                    <option value="2">2 estrelas</option>
                    <option value="3">3 estrelas</option>
                    <option value="4">4 estrelas</option>
                    <option value="5">5 estrelas</option>
                </select>

                <label for="comentario">Comentário:</label>
                <textarea id="comentario" name="comentario" rows="4" required></textarea>

                <button type="submit">Adicionar Avaliação</button>
            </form>
        </section>

        <!-- Lista de Avaliações -->
        <section class="history-section">
            <h2>Histórico de Avaliações</h2>
            <ul id="historicoAvaliacoes">
                <!-- As avaliações serão adicionadas dinamicamente aqui -->
            </ul>
        </section>
        <button class="back-button" onclick="goBack()">Voltar</button>
    </main>

    <footer class="footer-info">
        <p>&copy; 2023 ABOA App. Todos os direitos reservados.</p>
    </footer>

    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script>
        function navigateTo(page) {
            window.location.href = page;
        }

        function adicionarAvaliacao(event) {
            event.preventDefault();

            const usuario = $('#usuario').val();
            const festa = $('#festa').val();
            const avaliacao = $('#avaliacao').val();
            const comentario = $('#comentario').val();

            $.ajax({
                url: '/api/adicionar_avaliacao',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({ usuario, festa, avaliacao, comentario }),
                success: function (response) {
                    console.log(response.message);
                    listarAvaliacoes();
                },
                error: function (error) {
                    console.error('Erro ao adicionar avaliação:', error);
                }
            });
        }

        function listarAvaliacoes() {
            $.get('/api/listar_avaliacoes', function (data) {
                const historicoAvaliacoes = $('#historicoAvaliacoes');
                historicoAvaliacoes.empty();

                data.avaliacoes.forEach(function (avaliacao) {
                    historicoAvaliacoes.append(`
                        <li>
                            <p>${avaliacao.usuario}, ${avaliacao.festa}</p>
                            <p>Avaliação: ${avaliacao.avaliacao} estrela(s)</p>
                            <p>Comentário: ${avaliacao.comentario}</p>
                        </li>
                    `);
                });
            });
        }

        function goBack() {
            window.history.back();
        }

        $(document).ready(function () {
            listarAvaliacoes();
        });
    </script>
</body>
</html>

React: weird bug with drag n drop

So I have this little ugly bug, that makes my drag n drop ugly. Once, at the beginning of mouse move, the draggable jumps far below the cursor and then immediately comes back, so the drag n drop works all fine.
The draggable and the parent element are all relative positioned.

As I said, everything is fine, except that little bug in the beginning of dragging, that makes it really ugly. Like a blink.

GIF Demo:
the blinks are so fast, the my gif capturer only captured the third one

The code is below small references:

tokenTop = tokenRef.current!.getBoundingClientRect().top
I set “tokenTop” on Mouse Down on draggable object. I set it with React state.

  function handleMouseMove(event: MouseEvent) {
    if (!tokenReleased && tokenRef.current) {
      setInitialMousePos(event.clientY - tokenTop);

      if (parentElement && parentElement.classList.contains("battlefieldRow")) {
        setInitialTokenY(tokenTop - parentElement.offsetTop);
        const parentY = parentElement.offsetTop + 6;
        const newPos = initialMousePos + tokenTop - parentY;

        const bottomBoundary =
          parentElement.clientHeight - tokenRef.current.clientHeight - 6.1;

        if (initialTokenY) {
          if (newPos >= 5 && newPos <= bottomBoundary) {
            tokenRef.current.style.top = newPos - initialTokenY + "px";
          }
        }
      }
    }
  }

Don’t really know what to do and where to start :S
ChatGPT is not helpful either…