How to make a customized bullet text box in HTML/Javascript?

I am trying to make a custom text box in HTML/Javascript with the following requirements:

  • The text box’s initial state will be a single bullet point like this:
    enter image description here
  • Every line must start with a bullet point, so when the user types “enter” it will go to a new line and automatically start it with a bullet point
  • If they press “backspace” on an empty line with only a bullet point, it deletes the bullet point and returns to the end of the previous line
  • Bullet points are idented with “tab”
  • Bullet points are un-idented with “shift + tab”
  • Bullet points can only be indented once
  • Supports copy and pasted text

The following image is a word text box that I am trying to emulate:
enter image description here

I have tried a couple of solutions, but none seem to work the way I want. Is there something easy I am missing?

Read html based upon contents of a txt file

Need some Javascript help. Here is some code that reads a text file (Current-Week.txt) with a single record and then appends the contents of that record on the end of another filename. It then reads the concatenated filename (e.g. Standings-Week3.htm) into my page as html.

I can’t seem to get this to work

<script>
async function loadHtml() {
    const weekFile = await fetch("Current-Week.txt")
    const weekNbr = await respones.text()

    const fileName = "Standings-Week" + weekNbr
    const response = await fetch(fileName)

    const text = await response.text()
    document.getElementById('elementID').insertAdjacentText('beforeend', text)
}

loadHtml()
</script>

<div id='elementID'> </div>

Why are prevButton and nextButton removed from past queries once a new query is made?

In a sense, this is chatbox application. My prevButton and nextButton are removed from past queries once a new query is made so the pagination only works on the current query but I would like to be able to refer to past queries instead of having to ask the query again just to use the pagination

let page = 1;
let allResults = JSON.parse('{{ result|tojson|safe }}');
let itemsPerPage = 1;
var queryId = 0;
let queryState = null;

// Retrieve the existing data
let storedData = sessionStorage.getItem('resultsHistory');

// If there's no existing data, create a new object
// Otherwise, parse the existing data
let resultsHistory = storedData ? JSON.parse(storedData) : {};

window.onload = function() {
  var container = document.querySelector('.container');
  container.scrollTop = container.scrollHeight;

  fetchData();

}

function renderState(queryState) {
  // Check if the state object exists
  if (queryState) {
    // Render the state
    console.log('Query state')
    console.log(resultsHistory);
  } else {
    console.error('No state found for queryId: ' + queryId);
  }
}

function fetchData() {
  // Get the queryId from localStorage
  queryId = localStorage.getItem('queryId');
  if (queryId === null) {
    queryId = 0;
  } else {
    queryId = parseInt(queryId);
  }

  queryId++;
  console.log('Current queryId: ' + queryId);

  // Save the queryId to localStorage
  localStorage.setItem('queryId', queryId.toString());
  let data = allResults.slice()
  queryState = {
    total_pages: Math.ceil(data.length / itemsPerPage),
    current_page: 1,
    results: data,
    queryId: queryId
  };

  resultsHistory[queryId] = queryState;
  console.log(resultsHistory[queryId]);

  // Store the updated history
  sessionStorage.setItem('resultsHistory', JSON.stringify(resultsHistory));

  var queryDiv = document.querySelector('.query');
  if (!queryDiv) {
    // If no 'queryDiv' exists, create a new one
    queryDiv = document.createElement('div');
    queryDiv.className = 'query';
    queryDiv.id = 'query' + queryId;
    document.querySelector('.container').appendChild(queryDiv);
  }

  // Check if a 'buttonsContainer' already exists
  var buttonsContainer = document.querySelector('.buttonsContainer');
  if (!buttonsContainer) {
    // If no 'buttonsContainer' exists, create a new one
    buttonsContainer = document.createElement('div');
    buttonsContainer.className = 'buttonsContainer';
    document.querySelector('.container').appendChild(buttonsContainer);
  }

  // Create a new 'buttonsDiv' for this query
  var buttonsDiv = document.createElement('div');
  buttonsDiv.className = 'buttons';
  buttonsDiv.id = 'buttons' + queryId;
  buttonsDiv.dataset.queryId = queryId; // Store the queryId as a data attribute
  buttonsContainer.appendChild(buttonsDiv);

  // Create the previous and next buttons for this query
  let prevButton = document.createElement('button');
  prevButton.id = 'prevButton' + queryId;
  prevButton.textContent = 'Previous';
  buttonsDiv.appendChild(prevButton);

  let nextButton = document.createElement('button');
  nextButton.id = 'nextButton' + queryId;
  nextButton.textContent = 'Next';
  buttonsDiv.appendChild(nextButton);

  fetchPage(queryId, 1);
  addPaginationEventListeners(queryId, prevButton, nextButton, buttonsDiv);
  // generatePaginationButtons(queryId, queryState);
}


function addPaginationEventListeners(queryId, prevButton, nextButton, buttonsDiv) {
  prevButton.addEventListener('click', function() {
    var queryId = this.parentElement.dataset.queryId;
    if (resultsHistory[queryId].current_page > 1) {
      resultsHistory[queryId].current_page--;
      fetchPage(queryId, resultsHistory[queryId].current_page);
      renderState(resultsHistory[queryId]);
    }
  });

  nextButton.addEventListener('click', function() {
    var queryId = this.parentElement.dataset.queryId;
    if (resultsHistory[queryId].current_page < resultsHistory[queryId].total_pages) {
      resultsHistory[queryId].current_page++;
      fetchPage(queryId, resultsHistory[queryId].current_page);
      renderState(resultsHistory[queryId]);
    }
  });
}

function fetchPage(queryId, pageNumber) {
  let start = (pageNumber - 1) * itemsPerPage;
  let end = start + itemsPerPage;
  let data = resultsHistory[queryId].results.slice(start, end);

  // Update the current page number
  resultsHistory[queryId].current_page = pageNumber;

  populateTable(data);
}

function populateTable(data) {
  let tableBody = document.getElementById('myTable').getElementsByTagName('tbody')[0];
  tableBody.innerHTML = '';

  for (let item of data) {
    for (let [key, value] of item) {
      let row = document.createElement('tr');
      let cellKey = document.createElement('td');
      let cellValue = document.createElement('td');
      cellKey.textContent = key;
      cellValue.textContent = value;
      row.appendChild(cellKey);
      row.appendChild(cellValue);
      tableBody.appendChild(row);
    }
  }
}
<div class="common-buttons-container"></div>

I’ve created a new set of buttons with a unique id for each query and appended them to the specific ‘queryDiv’ of that query

Detect timestamp changes in React Native

We are currently developing an attendance management application and the core functionality is for the user to check in and check out through the app even when they’re offline.

The problem we’re facing right now is of the timestamp. User can change their device time and that changed time is reflected on the app manipulating the core purpose of the app. According to my research I don’t think we can prevent it, just looking for ideas that how can we solve this problem or if is there any work around you guys can think of.

Thanks

Passkey with typescript library simplewebauthn & password manager

I have implemented Passkey in ts with the library https://simplewebauthn.dev/docs/

It saved passkey in my browser Keychain or mac keychain.

But I also want that my password manager (dashlane, 1password,…) save it like for this site https://example.hanko.io/

How can I setup GenerateRegistrationOptions in order to be compatible with Password manager?

I try many combo like the following code. Is it elsewhere in the code?

// see for options https://simplewebauthn.dev/docs/packages/server
      authenticatorSelection: {
        residentKey: "preferred",
        /**
         * Wondering why user verification isn't required? See here:
         *
         * https://passkeys.dev/docs/use-cases/bootstrapping/#a-note-about-user-verification
         */
        userVerification: "preferred",
      }

Tesseract.js OCR How do I properly set Page Segmentation Mode (PSM, pageseg) to detect a single number in an image

I’ve been using tesseract to read various numbers (up to 99,999.9) in the format below:

enter image description here

It seems to get a proper read about 85% of the time, but I need 100% accuracy.

async function runOCR(url) {
    const worker = await Tesseract.createWorker('eng', 1, {
        tessedit_pageseg_mode: 13,
        config: '--psm 13'
    });

    (async () => {
        await worker.load();
        await worker.loadLanguage('eng');
        await worker.initialize('eng');    
        
        await worker.setParameters({
            tessedit_ocr_engine_mode: Tesseract.OEM_TESSERACT_ONLY,
            tessedit_char_whitelist: '0123456789,.',
            preserve_interword_spaces: '0',
            SINGLE_WORD: true,
            tessedit_pageseg_mode: Tesseract.SINGLE_WORD,
        });
        const {
            data: { text },
        } = await worker.recognize(url);
        doSomething(text);
        await worker.terminate();
    })();
}

The main issue is I don’t know where to set the Page Segmentation Mode (PSM, pageseg). The examples I’m finding are either out of date or in another language.

Here’s a pageseg options list that I found from a C file (https://github.com/tesseract-ocr/tesseract/blob/4.0.0/src/ccstruct/publictypes.h#L163)

  PSM_OSD_ONLY,       ///< Orientation and script detection only.
  PSM_AUTO_OSD,       ///< Automatic page segmentation with orientation and
                      ///< script detection. (OSD)
  PSM_AUTO_ONLY,      ///< Automatic page segmentation, but no OSD, or OCR.
  PSM_AUTO,           ///< Fully automatic page segmentation, but no OSD.
  PSM_SINGLE_COLUMN,  ///< Assume a single column of text of variable sizes.
  PSM_SINGLE_BLOCK_VERT_TEXT,  ///< Assume a single uniform block of vertically
                               ///< aligned text.
  PSM_SINGLE_BLOCK,   ///< Assume a single uniform block of text. (Default.)
  PSM_SINGLE_LINE,    ///< Treat the image as a single text line.
  PSM_SINGLE_WORD,    ///< Treat the image as a single word.
  PSM_CIRCLE_WORD,    ///< Treat the image as a single word in a circle.
  PSM_SINGLE_CHAR,    ///< Treat the image as a single character.
  PSM_SPARSE_TEXT,    ///< Find as much text as possible in no particular order.
  PSM_SPARSE_TEXT_OSD,  ///< Sparse text with orientation and script det.
  PSM_RAW_LINE,       ///< Treat the image as a single text line, bypassing
                      ///< hacks that are Tesseract-specific.

How can I better detect the numbers in the image OR how do I set the Page Segmentation Mode / config correctly? (The config changes I’ve been making don’t seem to make a difference in my hit rate)

Trouble setting es2022 in a new node js project

hopefully you’ll know whats happening.

I’m using a express project ts generator by seanpmaxwell to generate a new project

(Node version I’m using is v20.11.1)

It works just great, but I want to use es2022 on this (just want to get top level await working)

I have spent 3 days on this and its a total headache

I run yarn dev and this is the output

enter image description here

this is the package.json:

{
  "name": "server",
  "version": "0.0.0",
  "type":"module",
  "scripts": {
    "build": "npx ts-node build.ts",
    "lint": "npx eslint --ext .ts src/",
    "lint:tests": "npx eslint --ext .ts spec/",
    "start": "node -r module-alias/register ./dist/src --env=production",
    "dev": "nodemon",
    "test": "nodemon --config ./spec/nodemon.json",
    "test:no-reloading": "npx ts-node --files -r tsconfig-paths/register ./spec"
  },
  "nodemonConfig": {
    "watch": [
      "src"
    ],
    "ext": "ts, html",
    "ignore": [
      "src/public"
    ],
    "exec": "./node_modules/.bin/ts-node --files -r tsconfig-paths/register ./src"
  },
  "_moduleAliases": {
    "@src": "dist"
  },
  "engines": {
    "node": ">=8.10.0"
  },
  "dependencies": {
    "@hocuspocus/server": "^2.11.3",
    "@types/express-ws": "^3.0.4",
    "bcrypt": "^5.1.1",
    "cookie-parser": "^1.4.6",
    "dotenv": "^16.4.5",
    "express": "^4.19.2",
    "express-async-errors": "^3.1.1",
    "express-ws": "^5.0.2",
    "helmet": "^7.1.0",
    "inserturlparams": "^1.0.1",
    "jet-logger": "^1.3.1",
    "jet-paths": "^1.0.6",
    "jet-validator": "^1.1.1",
    "jsonfile": "^6.1.0",
    "jsonwebtoken": "^9.0.2",
    "module-alias": "^2.2.3",
    "moment": "^2.30.1",
    "morgan": "^1.10.0",
    "mysql2": "^3.9.3",
    "ts-command-line-args": "^2.5.1",
    "y-protocols": "^1.0.6",
    "yjs": "^13.6.14"
  },
  "devDependencies": {
    "@types/bcrypt": "^5.0.2",
    "@types/cookie-parser": "^1.4.7",
    "@types/express": "^4.17.21",
    "@types/find": "^0.2.4",
    "@types/fs-extra": "^11.0.4",
    "@types/jasmine": "^5.1.4",
    "@types/jsonfile": "^6.1.4",
    "@types/jsonwebtoken": "^9.0.6",
    "@types/morgan": "^1.9.9",
    "@types/node": "^20.12.2",
    "@types/supertest": "^6.0.2",
    "@typescript-eslint/eslint-plugin": "^7.4.0",
    "@typescript-eslint/parser": "^7.4.0",
    "eslint": "^8.57.0",
    "eslint-plugin-node": "^11.1.0",
    "find": "^0.3.0",
    "fs-extra": "^11.2.0",
    "jasmine": "^5.1.0",
    "nodemon": "^3.1.0",
    "supertest": "^6.3.4",
    "ts-node": "^10.9.2",
    "tsconfig-paths": "^4.2.0",
    "typescript": "^5.4.3"
  }
}

and this is the tsconfig.json

{
  "ts-node": {
    "esm": true,
 },
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */
    /* Basic Options */
    // "incremental": true,                   /* Enable incremental compilation */
    "target": "es2022",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "es2022",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    // "lib": [],                             /* Specify library files to be included in the compilation. */
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
    // "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    "outDir": "dist",                        /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                     /* Enable project compilation */
    // "tsBuildInfoFile": "./",               /* Specify file to store incremental compilation information */
    // "removeComments": true,                /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,                           /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* Enable strict null checks. */
    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
    // "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
    // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

    /* Module Resolution Options */
    "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
    // "allowUmdGlobalAccess": true,          /* Allow accessing UMD globals from modules. */

    /* Source Map Options */
    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */

    /* Advanced Options */
    "skipLibCheck": true,                     /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true,  /* Disallow inconsistently-cased references to the same file. */
    "paths": {
      "@src/*": [
        "src/*",
        "db/*"
      ],
    },
    "useUnknownInCatchVariables": false
  },
  "include": [
    "src/**/*.ts",
    "db/*.ts",
    "spec/**/*.ts",
    "build.ts"
  ],
  "exclude": [
    "src/public/"
  ]
}

if you got any other way to start a express project using js and latest es (or es2022) I’m open to new ideas, so far this is the most complete generator I found but I haven’t been able to progress further.

thanks

Is it possible to use JS to set the value of a React + downshift autocomplete dropdown?

OBJECTIVE

I’m a support agent trying to create a Chrome Extension to automate the filling out of Zendesk forms to make my job easier. I’m using the console at the moment.

SITUATION

Unfortunately, Zendesk uses React + downshift, which is complicating things as I am a newb at React and never used downshift. When I try to do it using normal means like changing the .value property and then dispatching events, the value change never registers.

WHAT I’VE TRIED

First of all, I simulate a click on the outer container, which opens the dropdown as expected.

  • Different combinations of dispatched events like first input, then change
  • Typing in the text by using keydown events to input the letters one by one
  • Using the blur event
  • Simulating a click on the actual input itself after the first simulated click on the parent
  • Both focusing on the input itself and not

FORM ELEMENT HTML

<div id="ember3412" class="ember-view">
    <!---->
    <div data-garden-id="forms.field" data-garden-version="8.74.3" data-test-id="ticket-form-field-dropdown-field-29533817" aria-describedby="7val-tooltip_1.0.6" data-garden-container-id="containers.tooltip" data-garden-container-version="1.0.6" class="sc-anv20o-3 gAALKx StyledField-sc-12gzfsu-0 glOpOr">
        <label data-garden-id="forms.input_label" data-garden-version="8.74.3" data-garden-container-id="containers.tooltip" data-garden-container-version="1.0.6" id="downshift-5-label" for="downshift-5-input" tabindex="0" aria-describedby="8val-tooltip_1.0.6"
        class="sc-anv20o-4 iIWDoF StyledLabel-sc-2utmsz-0 bYrRLL">HO Assignee*</label>
        <div data-garden-id="dropdowns.faux_input" data-garden-version="8.54.3" aria-invalid="false" aria-disabled="false" aria-haspopup="listbox" data-toggle="true" aria-expanded="false" aria-labelledby="downshift-5-label" data-test-id="ticket-form-field-dropdown-button"
        class="StyledTextInput-sc-k12n8x-0 sc-anv20o-0 kptXaI StyledFauxInput-sc-1l592ed-0 iJWzSI StyledTextFauxInput-sc-yqw7j9-0 gdXore">
            <div data-garden-id="dropdowns.select" data-garden-version="8.54.3" class="StyledSelect-sc-xifmwj-0 eSliJF"><span class="sc-anv20o-1 hGMRMW"><div data-garden-id="typography.ellipsis" data-garden-version="8.74.0" title="-" class="StyledEllipsis-sc-1u4uqmy-0 gxcmGf">-</div></span></div>
            <input data-garden-id="dropdowns.input" data-garden-version="8.54.3"
            aria-invalid="false" data-garden-container-id="containers.field.input" data-garden-container-version="3.0.15" id="downshift-5-input" aria-labelledby="downshift-5-label" aria-autocomplete="list" autocomplete="off" role="combobox" class="StyledInput-sc-hzhvmp-0 etSNgg StyledTextInput-sc-k12n8x-0 jEqqcP"
            value="">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" focusable="false" viewBox="0 0 16 16" aria-hidden="true" data-garden-id="forms.media_figure" data-garden-version="8.74.3" class="StyledTextMediaFigure-sc-1qepknj-0 lnDzQq">
                <path fill="currentColor" d="M12.688 5.61a.5.5 0 01.69.718l-.066.062-5 4a.5.5 0 01-.542.054l-.082-.054-5-4a.5.5 0 01.55-.83l.074.05L8 9.359l4.688-3.75z"></path>
            </svg>
        </div>
    </div>
</div>

REACT DEV TOOLS HIERARCHY

The actual input element itself is the one indicated by the arrow:

enter image description here

CODE

I’ve tried many, many things but this is the first thing I tried:

function insertText(parent, text, selectorDescription) {
    if (!parent) {
        console.error(`Parent not found for ${selectorDescription}`);
        return;
    }

    let element = parent.querySelector('input');

    if (!element) {
        console.error(`Input field not found for ${selectorDescription}`);
        return;
    }

    element.click(); // tried with and without
    element.focus(); // tried with and without
    
    element.value = text;

    element.dispatchEvent(new Event('input', { bubbles: true, cancelable: true  }));
    element.dispatchEvent(new Event('change', { bubbles: true, cancelable: true  }));
}

What am I doing wrong? What is the correct approach in this context?

Fetching Hashtag Content with Instagram Graph API Returns Inconsistent Status Codes

I’m working with the Instagram Graph API to fetch content associated with specific hashtags. I’ve already set up my access token and business ID, and my code is intended to retrieve posts using the related hashtag. However, I’m encountering an issue where the API responses are inconsistent: sometimes I receive a 200 status code, indicating success, but at other times I get a 400 status code. Occasionally, the response message is “sorry, content is unavailable.” I believe my setup for the hashtag ID is correct but I’m unsure if I’m missing any required permissions or if there’s another issue at play.

Are there specific permissions required for fetching hashtag content that I might be missing?

Could the inconsistency in the API responses be related to the way I’ve set up the hashtag ID, or is it likely due to another issue?

Has anyone else experienced similar inconsistencies when using the Instagram Graph API for hashtag content, and how were you able to resolve it?

What I’ve tried:

Double-checking the access token and business ID to ensure they’re correctly set up.
Verifying the hashtag ID is correct and relates to the content I’m trying to fetch.
Looking for documentation on required permissions specifically for hashtag content but haven’t found clear guidelines.

How to fix “Error: listen EADDRINUSE: address already in use :::5000” ‘error’ event

node:events:495
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE: address already in use :::5000
    at Server.setupListenHandle [as _listen2] (node:net:1817:16)
    at listenInCluster (node:net:1865:12)
    at Server.listen (node:net:1953:7)
    at Function.listen (/Users/parthsojitra/Desktop/Final_SMCar/Final_SMCar/Final_SMCar/SM_Car-API/node_modules/express/lib/application.js:635:24)
    at Object.<anonymous> (/Users/parthsojitra/Desktop/Final_SMCar/Final_SMCar/Final_SMCar/SM_Car-API/index.js:50:5)
    at Module._compile (node:internal/modules/cjs/loader:1256:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
    at Module.load (node:internal/modules/cjs/loader:1119:32)
    at Module._load (node:internal/modules/cjs/loader:960:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:86:12)
Emitted 'error' event on Server instance at:
    at emitErrorNT (node:net:1844:8)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  code: 'EADDRINUSE',
  errno: -48,
  syscall: 'listen',
  address: '::',
  port: 5000
}

tell me what to do

React/HTML: onMouseDown does not fire until after the mouse is released

EDIT: possibly a dupe of this: How can I make Mousedown/Mouseup trigger on mobile devices?

I am losing my mind trying to troubleshoot this extremely bizarre behavior.

In this setup, “onMouseDown” will not appear in the log until after I release the mouse. I am on Chrome with Linux Mint.

EDIT: Here’s a huge clue as to what’s going on that I just discovered. This is only happening when I go into the Chrome dev tools and click on “toggle device toolbar” which puts the screen into mobile mode.

Code:

  useEffect(() => {
    const onMouseUp = () => {
      console.log('onMouseUp')
    }

    const onMouseDown = () => {
      console.log('onMouseDown')
    }

    window.onmouseup = onMouseUp
    window.onmousedown = onMouseDown

    return () => {
      window.onmouseup = null
      window.onmousedown = null
    }
  }, [])

Does anybody have any insight into this? I am completely at a loss here.

How detect position:sticky is triggered when target element is not on top:0 position

I’ve already use this solution with IntersectionObserver (top:-1px + IntersectionObserver ), but it works only if target sticky element positioned as top:0 – in my case

I have two sticky elements with different top position and sticked together: How to do the same trick with sticky detection for nav element also?

    // header sticky detection hack
    const observer = new IntersectionObserver( 
    ([e]) => e.target.classList.toggle("is-sticky", e.intersectionRatio < 1),
    { 
        threshold: [1] }
    );
    observer.observe(document.querySelector('header'));

    // how to do that with nav element?
body {
   min-height: 200vh
}

.styled {
    width: 100%;
    text-align: center;
    text-transform: uppercase;
    display: flex;
    justify-content: center;
    align-items: center;
}
header {
    background: #ccc;
    height: 72px;
    position: sticky;
    top:-1px; /* trick */
}
header.is-sticky {
   background: yellow;
}
.hero {
    height: 400px;
    background: #ddd;
    width: 100%;
}
nav {
   background: #bbb;
   height: 36px;
   position: sticky;
   top:72px;
   width: 100%;
}
nav.is-sticky {
   background: green;
}
<header class="styled">HEADER</header>
<div class="hero styled">SOME CONTENT</div>
<nav class="styled">NAVIGATION</nav>

My loadall function works but my line by line loadEmployeeData function is not working for one function but not an other?

So loadAllEmployeeData works but for some reason and renders correctly in my webpage but the loadEMployeeData one just does nothing…I think it may have to do with the const employeeDbArray?

document.addEventListener('DOMContentLoaded', function() {
    renderAlphabetLinks();
});

document.addEventListener('DOMContentLoaded', function() {
    myTime();
});

function renderAlphabetLinks() {
    const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    const container = document.getElementById('alphabetLinks');
    let html = '';
    for (let letter of alphabet) {
        html += `<a href="#" onclick="loadEmployeeData('${letter}')">${letter}</a> `;
    }
    html += `<a href="#" onclick="loadAllEmployeeData()">ALL</a>`;
    container.innerHTML = html;
}

async function loadEmployeeData(letter) {  
    try {
        const response = await fetch('/employees');
        const data = await response.text();
        const employeeDbArray = data.split("n").filter(name => name.toUpperCase().startsWith(letter));
        const targetDiv = document.getElementById('employeeList');
        targetDiv.innerHTML = employeeDbArray.join('<br>');
    } catch (error) {
        console.error('Error fetching employee data:', error);
    }
}

async function loadAllEmployeeData() {
    try {
        const response = await fetch('/employees');
        const data = await response.text();
        const targetDiv = document.getElementById('employeeList');
        targetDiv.innerHTML = data.split("n").join('<br>');
    } catch (error) {
        console.error('Error fetching all employee data:', error);
    }
}


}

Google map – Using Javascript API – How to highlight disputed countries

We are a nonprofit organization who would like to highlight all the countries where we sent our donations, including countries with disputed borders, like Kosovo.

We are using the Google Maps Platform with the Javascript API.
We use the feature layer “Country” to change the style of selected countries.
Everything works fine for countries that are not disputed.

We tried to use the same pattern for disputed countries that we use for other countries but with no success. We are unable to change the style of disputed countries and we can’t even listen to the mouse-over event for displaying a proper tooltip.

Is this can be done ?
Any suggestions on how we can do it using google map ?