Looping elements and sequentially clicking on children

I’m trying to automate a task through Firefox’s console in Developer Tools by running some jQuery code.

First, an example of the nodes I need to loop through. Note inline comments. There are nodes where the button has a span that doesn’t contain the word Cycling and should be skipped.

<div class="ActivityListItem_activityType__qQkN4">
    <button>
        <span class="ActivityListItem_activityTypeText__jWs2o">Cycling</span>
        <span class="InlineEditDropdown_iconPointerDown__0bK4V ActivityListItem_isHidden__2pG6N"><i
                class="icon-pointer-down"></i>
        </span>
    </button>

    <!-- dynamically added after clicking above button -->
    <ul class="InlineEditDropdown_dropdownContainer__E5M6g" role="menu">
        <!-- omitted children li -->
        <li class="InlineEditDropdown_dropdownItem__WkY6H null null" tabindex="0"><a href="#" role="menuitem">Mountain Biking</a></li>
        <!-- omitted children li -->
    </ul>
</div>

The steps that seem to need to be replicated:

  1. click the button, which fires and event and makes a list appear
  2. from the list, click the option wanted which fires another event

The script I’m running in the console:

var script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-3.6.0.min.js';
document.head.appendChild(script);

var x = 0;
//select using start of the class name
$('div[class^="ActivityListItem_activityType"]').each(function(x){
    //alert("here..."+x); //outputs incremented value
    
    //click to make the list appear
    $(this).children('button span:contains("Cycling")').click();
    
    //click the right li to launch event
    $(this).children('ul li a:contains("Mountain Biking")').click();
});

No errors, but I’m not seeing much happen either (other than the alert when it’s enabled).

Assuming my selectors are wrong? Perhaps I’m misunderstanding how to use .children()?

How to render on nodejs server side?

Given this server.ts code:

import 'ignore-styles';
import register from '@babel/register';
import express from "express";
import fs from "fs";
import path from "path";
import ReactDOMServer from "react-dom/server";
import App from "./src/App";

register({
  ignore: [/(node_modules)/],
  extensions: ['.ts', '.tsx'],
  presets: ['@babel/preset-env', '@babel/preset-react', '@babel/preset-typescript'],
});

const app = express();

app.use("^/$", (req, res) => {
  fs.readFile(path.resolve("./build/index.html"), "utf-8", (err, data) => {
    if (err) {
      console.error(err);
      return res.status(500).send("Some error happened");
    }

    const renderedApp = ReactDOMServer.renderToString(<App />);
    return res.send(
      data.replace('<div id="root"></div>', `<div id="root">${renderedApp}</div>`)
    );
  });
});

app.use(express.static(path.resolve(__dirname, "..", "build")));

app.listen(3005, () => {
  console.log("App is launched");
});

I have the following syntax error:

'App' refers to a value, but is being used as a type here. Did you mean 'typeof App'?ts(2749)
type App = /*unresolved*/ any

And when I try to run the server app with npx tsx server.ts I get the following error:

[...]
> npx tsx server.ts


node:internal/modules/run_main:122
    triggerUncaughtException(
    ^
Error [TransformError]: Transform failed with 1 error:
[...]/server.ts:24:59: ERROR: Expected ">" but found "/"

The App component is stored in the /src folder:

import React from "react";

const App: React.FC = () => {
  return (
    <div className="app">
      <h1>Hello world</h1>
    </div>
  );
};

export default App;

together with the index.tsx

import React from "react";
import App from "./App";
import { hydrateRoot } from 'react-dom/client';


const container = document.getElementById('root');
const root = hydrateRoot(container, <App/>);

And the server.ts file is at the root of the repository, in the parent folder of src.

And this is my tsconfig.json file:

{
  "compilerOptions": {
    "target": "ESNext",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "ESNext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": [
    "src"
  ]
}

One more thing important to mention is that my VSC compiler is greying out the import of the App(import App from "../client/src/App";), so it doesn’t even see the <App /> from the code as the App from the import.

How can I get this working? I’m trying to render some react on server side using nodejs + express and I just can’t figure out what’s wrong with this one.
Any help will be much appreciated!

React Application Loading with Delay, Showing Blank Screen Initially

I’m working on a mid-level React project, and I’m facing an issue when the app is loaded for the first time on any device. Initially, the screen stays blank, and after some time, the entire page loads. This delay causes a poor user experience, especially on first visits.

What could be causing this issue, and how can I resolve it to improve the initial loading time and avoid the blank screen?

Here are a few things I’ve tried:

Ensured that assets (JS/CSS) are properly bundled.

Checked the network tab in Dev Tools for any slow resource loading.

I’m looking for suggestions on how to optimize the initial load and improve the perceived performance.

Leaflet React map does not load?

I tried to use a React Leaflet example and but it does not render map correctly. My codes is:

import './App.css';
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';

const App = () => {
  return (
    <MapContainer center={[51.505, -0.09]} zoom={13} scrollWheelZoom={false}>
      <TileLayer
        attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      />
      <Marker position={[51.505, -0.09]}>
        <Popup>
          A pretty CSS3 popup. <br /> Easily customizable.
        </Popup>
      </Marker>
    </MapContainer>
  );
}

export default App;

What I get is:

screenshot

Maybe you’ll say I do not have Leaflet CSS. But when I add the
import "leaflet/dist/leaflet.css" in main.jsx and also
.leaflet-container { width: 100%; height: 100vh; }
in App.css

the map does not appear at all. Now I get:
enter image description here

How can I fix my codes?

mapbox-gl-js creates artifacts in corner with geojson data (only when screen height is > 1024px)

Minimum reproducible example:

I am using mapbox-gl-js on a website (angular)

I am using this dataset for the MRE (minimum reproducible example):

Here is the github repo:
https://github.com/folsze/mapbox-gl-js-world-map-artifact

How to reproduce:

  1. clone project
  2. in terminal: npm i
  3. in terminal: npm run start
  4. open browser inspect tools
  5. select device to “responsive”
  6. set screen height to > 1024 px (e.g. 1025 px)
  7. zoom all the way out on the map (mousewheel)

Then you will see the artifact here, at the world wrap:

enter image description here

Note:
I am getting the data from here:
https://www.naturalearthdata.com/downloads/50m-cultural-vectors/50m-admin-0-countries-2/

and converted shpfile to geojson using the QGIS software

here is the resulting data:

https://github.com/folsze/mapbox-gl-js-world-map-artifact/blob/main/src/assets/a.geojson

(note: you can even see the issue in the data itself on the github OSM-viewer, so I guess it’s not the libraries fault but the data has some issues)

(drop into layers, right click feature, Export->Save Feature As…-> GeoJson)

Note:

Here is my relevant code:

HTML:

<ion-content [fullscreen]="true">
  <div id="map"></div>
</ion-content>

CLASS:

import { Component } from '@angular/core';
import { IonContent } from '@ionic/angular/standalone';
import * as mapboxgl from 'mapbox-gl';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
  imports: [IonContent],
})
export class HomePage {

  map!: mapboxgl.Map;
  features: any[] = [];

  constructor() {}

  ngOnInit() {
    fetch('/assets/a.geojson')
      .then(response => response.json())
      .then(data => {
        this.features = data.features;
        this.initializeMap(data);
      });
  }

  initializeMap(geojsonData: any) {
    this.map = new mapboxgl.Map({
      attributionControl: false,
      accessToken: 'pk.eyJ1IjoiZmVsaXhvbHN6ZXdza2kiLCJhIjoiY2xyNTZrOTJvMWcxeTJrbnZsM2RuOGk5aiJ9.TENtwqeAtqAqSNzFmg0i4w',
      container: 'map',
      style: {
        version: 8,
        glyphs: 'mapbox://fonts/mapbox/{fontstack}/{range}.pbf',
        sources: {
          'countries': {
            type: 'geojson',
            data: geojsonData,
            promoteId: 'admin',
          }
        },
        layers: [
          {
            id: 'background',
            type: 'background',
            paint: {
              'background-color': '#c6ecff'
            }
          },
          {
            id: 'country-fills',
            type: 'fill',
            source: 'countries',
            paint: {
              'fill-color': '#2e34da',
              'fill-opacity': 1
            }
          },
          {
            id: 'country-borders',
            type: 'line',
            source: 'countries',
            paint: {
              'line-color': '#000',
              'line-width': 0.5,
            }
          }
        ]
      },
      center: [-84.077922, 10.0651],
      zoom: 7
    });

  }

}

On click of button the background color of div does not change

I have a simple program where, on the click of button, I expect the background of my component color to change, but it does not. Where am I making mistake?

import { useState } from "react";
import './sixth.css';

const Sixth = () => {

    const [bgColor, setBgColor] = useState("white"); 

    const bgFunc = (val)=> {
        setBgColor(val); 
    }

    return (
        <div className="sixth" style={{'background': {bgColor}}}>
            <button onClick={()=> bgFunc("red")}>red</button>
            <button onClick={()=> bgFunc("green")}>green</button>
            <button onClick={()=> bgFunc("blue")}>blue</button>
        </div>
    )
}

export default Sixth;

Terminal Layout Library

What I need

For one card-game prototype I’m developing I need module that would handles user interface in terminal.

I want to display pretty and aligned layout of game board and allow user to interact with it using keys and arrows. It’s worth pointing out that layout of game board is more complex then simple table.

Attempted Solution

I wrote small library that work like this:

  1. Switch terminal into raw + alternate mode (using curses gem)
  2. Print A thing based on data (supposedly board layout)
  3. Every time user presses a key we care about, update data
  4. Refresh screen and repeat from step 2

It also supports switching between scenes

Problem

My library is too low level to know how to print aligned layout or make it intractable. I don’t what to solve this problem myself.

Does anyone know library that does that? My project is written in Ruby, but I can rewrite it into JavaScript, so preferably one that works with those two languages.

Using 0 after selecting form to reset

I didn’t get why we use 0 after selecting form to rest in jquery?
Can anyone help

I tried on beforeSend method in Ajax jquery, but I found we can reset the total form with reset() option, and can show our messages too that we sent through json encode from php file

Calculadora de IMC – Primeiro projeto de HTML com CSS e JavaScript inline [closed]

Calculadora de IMC
Calculadora simples de IMC (Índice de Massa Corporal) feita com HTML, CSS e JavaScript.
Aqui está: https://nicolasbraganca.github.io/calculadora-imc/

Funcionalidade
Calcula o IMC a partir da altura e peso informados pelo usuário.
Exibe o resultado com base nas classificações da OMS.
Valor exibido é um número (índice), não uma porcentagem.
Observação
O IMC é um índice numérico, sem unidade ou símbolo de porcentagem. O resultado ajuda a identificar a faixa de peso da pessoa (normal, sobrepeso, etc).

Como usar
Informe sua altura (em metros).
Informe seu peso (em kg).
Clique em “Calcular”.
O resultado será exibido em forma de alerta.

Esse é o meu primeiro projeto postado aqui, embora eu ja tenha feito mais uns 2 em pouco mais de 2 semanas de estudos. Estou muito empolgado e feliz de estar conseguindo exercitar e aprender algo que eu tinha tanto medo. Então se você tem alguma dica, adendo ou até mesmo alguma palavra que vá me deixar ainda mais empolgado, espero que deixe aqui o seu comentário(nem sei se no github da para comentar haha).

Eu acredito que tenha conseguido exercer o que eu queria, embora precise de melhorias, estou orgulhoso desse projeto!
Adoraria de dicas de programação, tanto na parte de lógica de programação quanto de estudos iniciais!
Grato desde já!

Is bushatza a name [closed]

bushatzaneed to know what it is

I was thinking about it cause it keeps popping up is it what it looks like how do I know what to do with it if I could see where it’s coming from thenits possible I could fix what it is and stop it from happening

Parcel resolver-glob is not working as expected after upgrading to 2.14.4

I recently upgraded one of my project’s ParcelJS from version 2.13.3 to 2.14.4. Everything works as expected, except for the glob imports.

JS

import images from "../../../img/gallery/*.jpg";

export const data = [
    {
        id: 1,
        name: "Spread Sheets",
        files: "312",
    },
    {
        id: 2,
        name: "Documents",
        files: "4532",
    },
    {
        id: 3,
        name: "Downloaded Files",
        files: "15876",
    },
    ...
];

data.forEach((item) => {
    filePreview = `<div class="h-24 w-100">
                        <img src="${images[item.img]} " alt="">
                   </div>`;

    ...
});

.parcelrc

{
    "extends": "@parcel/config-default",
    "resolvers": [
        "@parcel/resolver-glob",
        "..."
    ]
}

After bulding, I see the images are not displaying and inspecting the image tags shows as below:

<img src="[object Object] " alt="">

Also, console.log(images), returns only the file names and not the path.

{
    "1": {},
    "2": {},
    "3": {},
    "4": {},
    "5": {},
    "6": {},
    "7": {},
    "8": {},
}

(Here, 1, 2, 3… are the image names.)


I’m experiencing this issue only after upgrading Parcel to version 2.14.4 — everything was working fine in 2.13.3, so I’m not sure what exactly I’m missing.

I’ve also updated the import statement to

import * as images from "../../../img/gallery/*.jpg";

But the issue remains the same.

Why are curly braces required when a function is returned inside a function?

This code from a tutorial is working so this is a general knowledge question.
In the return {logout} line, why are curly braces required? I know to use them when multiple objects are returned from the function, but is this necessary when only a single function is being returned?

import { useAuthContext } from './useAuthContext';

export const useLogoutContext = () => {
const { dispatch } = useAuthContext();
    const logout = () => {
        //remove user from storage
        localStorage.removeItem('user');
        //dispatch logout action
        dispatch({ type: 'LOGOUT' });
    };
    return { logout };
};
import { Link } from 'react-router-dom'
import { useLogout } from '../hooks/useLogout'

const Navbar = () => {
  const { logout } = useLogout()

  const handleClick = () => {
    logout()
  }

  return (
    <header>
      <div className="container">
        <Link to="/">
          <h1>Workout Buddy</h1>
        </Link>
        <nav>
          <div>
            <button onClick={handleClick}>Log out</button>
          </div>
          <div>
            <Link to="/login">Login</Link>
            <Link to="/signup">Signup</Link>
          </div>
        </nav>
      </div>
    </header>
  )
}

export default Navbar

I tried removing the curly braces and it broke the code.

Why do I get an error when making JavaScript documentation with WebDoc?

I’m trying to do a documentation for my JavaScript little library. Because I don’t like the JSDoc appearance, I wanted to use WebDoc (npmjs.org/@webdoc/cli). I’ve installed the latest version, but when I execute webdoc, I find this error :

C:UserstakvorianeDocumentsGitHubmathlib>webdoc
This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason:
Error: Path contains invalid characters: docs<webdoc.internal>src
    at checkPath (C:UserstakvorianeApplicationsNode.jsnode_modules@webdocclinode_modulesfs-extralibmkdirsmake-dir.js:20:21)
    at module.exports.makeDir (C:UserstakvorianeApplicationsNode.jsnode_modules@webdocclinode_modulesfs-extralibmkdirsmake-dir.js:45:3)
    at Object.<anonymous> (C:UserstakvorianeApplicationsNode.jsnode_modules@webdocclinode_modulesuniversalifyindex.js:21:10)
    at C:UserstakvorianeApplicationsNode.jsnode_modules@webdocclinode_modulesfs-extraliboutputindex.js:20:11
    at C:UserstakvorianeApplicationsNode.jsnode_modules@webdocclinode_modulesuniversalifyindex.js:21:38
@webdoc took 1849ms to run!

C:UserstakvorianeDocumentsGitHubmathlib>webdoc

Here is my webdoc.conf.json :

{
  "$schema": "https://webdoc.nyc3.digitaloceanspaces.com/schemas/v1/webdoc.conf.schema.json",
  "source": {
    "include": [
      "./src"
    ],
    "exclude": [
      "node_modules"
    ]
  },
  "template": {
    "applicationName": "Vanilla.js"
  }
}

And here is src/main.js :

/**
 * @function isMultiple
 * @description This function checks whether a number is a multiple of another number.
 * @param {number} a - The number that is maybe a multiple of the other
 * @param {number} b - The number that is maybe a divisor of the other
 * @returns {boolean}
 * @example
 * console.log(isMultiple(3, 6)) // True because 6 / 3 = 2 with remainder 0
 * console.log(isMultiple(5, 8)) // False because 8 / 5 = 1 with remainder 3
 */

export const isMultiple = (a, b) => {
    if (typeof a !== "number") {
        throw new TypeError(`'a' must be of type 'number', not '${typeof a}'.`)
    }

    if (typeof b !== "number") {
        throw new TypeError(`'b' must be of type 'number', not '${typeof b}'.`)
    }
    
    return b % a === 0
}

Why do I get this error and how can I fix it?