javascript – How to get Multi Selection direction it started from?

When developing using range in JavaScript, if you press the arrow key through keydown
How to get multi-selection direction it started from? (shift + > | shift + <)

Take the string “ABC” as an example

  1. Place the cursor between A and B, Press shift + > twice
    -> startOffset 2, endOffset 3 -> startOffset 1, endOffset 3
  2. Place the cursor after C, Press shift + < three times And Press shift + > once
    -> startOffset 0 endOffset3 -> startOffset 1, endOffset 3

Both have the same offset,

  1. endOffset has been changed and 2)startOffset has been changed.

How to get multi-selection direction from arrow keydown event?

In case of multi-select, Customize the cursor when press the arrow key.

window.addEventListener("keydown", function(e) {
  let range = window.getSelection().getRangeAt(0);
  if(e.keyCode == 37) { // arrow left <
     if(~~~) {
       range.setStart(~~);
       range.setEnd(~~);
     }
  } else if(e.keyCode == 39) { // arrow right >
    if(~~~) {
       range.setStart(~~);
       range.setEnd(~~);
     }
  }
});

Snapshot not actively listening. how to fix?

I’m following a simple firebase tutorial to get me back into coding. The tutorial taught how to use snapshot. i tried it but it doesn’t seems to work as intended. My intention was for it to actively listen for any changes and change it. Snapshot seems to not be able to do it.
Something like this: https://www.youtube.com/watch?v=rfQ2F8kQEUg&t=65s
Below is my code

index.html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>learning how to do firebase 9</title>
</head>
<body>
    <h1>Add Form</h1>

    <form class="add">
        <label for="title">Title:</label>
        <input type="Text" name="Title" id="title" required>

        <label for="author">Author</label>
        <input type="Text" name="Author" id="author" required>

        <label for="genre">Genre:</label>
        <input type="Text" name="Genre"  id="genre" required>

        <button>Add a new book</button>
    </form>

    <form class="delete">
        <label for="id"> Document id:</label>
        <input type="text" name="Id" id="id" required>
        <button> delete a book</button>
    </form>

    <script src="bundle.js"></script>
</body>
</html>

index.js

import {initializeApp} from 'firebase/app'
import {
    getFirestore, collection, onSnapshot,
    addDoc, deleteDoc, doc  
} from 'firebase/firestore'


// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  };

    // init firebase
   initializeApp(firebaseConfig)

   //init services
  const db = getFirestore()

   //collection ref
   const colRef = collection(db, 'books')

   //real time collection data
    onSnapshot(colRef, (snapshot) => {
        let books = []
        snapshot.docs.forEach((doc) => {
            books.push({ ...doc.data(), id: doc.id })
        })
        console.log(books)
    })

    //adding documents
    const addBookForm = document.querySelector('.add')
    addBookForm.addEventListener('submit', (e) =>{
        e.preventDefault()

        addDoc(colRef, {
            Title: addBookForm.Title.value,
            Author: addBookForm.Author.value,
            Genre: addBookForm.Genre.value
        })
        .then(() => {
            addBookForm.reset()
        })
    })

    //deleting documents
    const deletebookform = document.querySelector('.delete')
    deletebookform.addEventListener('submit', (e) => {
        e.preventDefault()

        const docRef = doc(db, 'books', deletebookform.id.value)

        deleteDoc(docRef)
        .then(() =>{
            deletebookform.reset()
        })
    })

What seems to be the issue. have been trying to debug myself for the past 1-2 weeks

Table header fixed top with using iscroll

I want to fix the table header with ISCROLL ( iscroll library) because I want to scroll in TOUCH as well. Now normal sticky fixed doesn’t work in it and. i have try many ways but didn’t achieve till now. can we do that any how. please help me.

I am not getting the proper event in the section I have added outside.

Threejs cube is black and has no unexpected light

I see other people demo has light but my local 5173 cannot see the light on some sides for the MeshPhongMaterial. I tested light position , tested pointlight , tested ambientlight and still cannot find the reason. I checked the code of other people demo, people usually use let in the website online for the demo instead of const but I think it does not matter. I cannot find the reason why the cube is always black and single color without light effect when rotating.

import './style.css'
import * as THREE from 'three';
import WebGL from 'three/addons/capabilities/WebGL.js';

// Initialize Three.js
const scene = new THREE.Scene();

const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0xeeeeee, 1.0) 
renderer.shadowMap.enabled = true 


document.body.appendChild(renderer.domElement);

const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 100);
camera.position.set(10, 10, 10); 
camera.lookAt(scene.position); 



// Add an ambient light to provide overall illumination
const ambientLight = new THREE.AmbientLight(0x404040, 1, 1000)
ambientLight.position.set(10, 10, -10)
scene.add(ambientLight)

const pointLight = new THREE.PointLight(0xffffff, 1,1000)
pointLight.position.set(5, 5, 5)
scene.add(pointLight)
     
const geometry = new THREE.BoxGeometry(1, 1, 1) 
const material = new THREE.MeshPhongMaterial({
    color: 0x0000ff
  })
const cube = new THREE.Mesh(geometry, material) 
cube.position.set(0, 1 , 0)
scene.add(cube)

const wireframeCube = new THREE.Mesh(
    new THREE.BoxGeometry(2, 2, 2),
    new THREE.MeshBasicMaterial({ color: 0xff0000, wireframe: true })
);
scene.add(wireframeCube);

function animate() {
    cube.rotation.x += 0.01
    cube.rotation.y += 0.01
  }

function render() {
    animate()
    requestAnimationFrame(render)
    renderer.render(scene, camera)
}

// Render the scene
renderer.render(scene, camera);

window.addEventListener('resize', function() {
    camera.aspect = window.innerWidth / window.innerHeight
    camera.updateProjectionMatrix()
    renderer.setSize(window.innerWidth, window.innerHeight)
  })


if ( WebGL.isWebGL2Available() ) {

    // Initiate function or other initializations here
    render()

} else {
    const warning = WebGL.getWebGL2ErrorMessage();
    document.getElementById( 'container' ).appendChild( warning );
  console.log('Not Support webgl');

}

[![a cube with no light][1]][1]
[1]: https://i.sstatic.net/65p8brtB.png

Identical(?) Tailwind vs Inline vs Stylesheet styles – Tailwind incorrect on initial render

I’ve got three grids, each with sliders as children.

  • 1 is styled with tailwind, here
  • 1 with inline styles, here
  • and 1 with a stylesheet here

If you look at the styles below, is there any reason for them to be rendering differently?
The Tailwind version renders incorrectly initially. You have to resize the window for it to display as the others do. I understand that sliders (in this case keen-slider) can be particular with their styling, but to my naive eye the styling looks exactly the same:

Tailwind:

<div className="slider-grid grid grid-cols-2 gap-4 p-4 w-[75%]">
  <div className="flex flex-col overflow-hidden max-w-[100%] gap-y-[10px]">
  </div>
</div>

Inline:

<div
  className="slider-grid"
  style={{
    display: "grid",
    gridTemplateColumns: "1fr 1fr",
    width: "75%",
    gap: "1rem",
    padding: "1rem",
  }}

    <div
      className="slider"
      style={{
        display: "flex",
        flexDirection: "column",
        overflow: "hidden",
        maxWidth: "100%",
        rowGap: "10px",
      }}
    >
  </div>
</div>

Stylesheet:

.slider-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  width: 75%;
  gap: 1rem;
  padding: 1rem;
}

.slider {
  display: flex;
  flex-direction: column;
  overflow: hidden;
  max-width: 100%;
  row-gap: 10px;
}

Tailwind on render:

Tailwind before

Tailwind after resize (exactly like both inline and stylesheet versions on initial render):
Tailwind after

My random number generator isn’t generating new numbers

My project includes a function that generates three random numbers from the basket and maps each to a button. The idea is that each time you press a button you will get three new numbers and the number you pressed will be removed from the array. However, whenever the startTurn function is called, it spits out the same 3 numbers.

const repeat = (arr, n) => Array(n).fill(arr).flat();
let basket = repeat(["red", "orange", "yellow", "green", "blue", "purple"], 3);

function newGame() {
  basket = repeat(["red", "orange", "yellow", "green", "blue", "purple"], 3);
  console.log(basket);
  startTurn();
}


const button1 = document.querySelector('#button1');
const button2 = document.querySelector('#button2');
const button3 = document.querySelector('#button3');
const button4 = document.querySelector('#new-game');

let turncount = 0;
let choice = [];

function startTurn(){
  while(choice.length <= 3){
    let r = Math.floor(Math.random() * (basket.length)) ;
    if(choice.indexOf(r) === -1) choice.push(r);
  }
  button1.style.backgroundColor = basket[choice[0]];
  button2.style.backgroundColor = basket[choice[1]];
  button3.style.backgroundColor = basket[choice[2]];
  console.log(basket.length);
  console.log(basket[choice])
}

Axios throws net::ERR_EMPTY_RESPONSE error when call API method

I got net::ERR_EMPTY_RESPONSE whenever API get called. It is a XHR request error

I used to run my node backend locally and it works fine. Now, I try to containerize it via docker. There are two containers: front and backend. I have no problem with my react frontend. Only node backend has the aforemention issue.

Here is my API post request function:

const signInCurrentUser = async (username, password) => {
    try {
        const response = await axiosInstance.post("/users/signin", {
            username,
            password,
        });

        console.log("Signed-in user: ", response);
        return response;
    } catch (error) {
        console.log("error: ", error);
        // Check if the error has a response object
        if (error.response) {
            if (error.response.status === 400) {
                throw new Error("Invalid username or password");
            } else {
                throw new Error(
                    `Sign-in failed with status code ${error.response.status}`
                );
            }
        } else if (error.request) {
            // The request was made but no response was received
            throw new Error("No response received from the server");
        } else {
            // Something happened in setting up the request
            throw new Error(`Error in request setup: ${error.message}`);
        }
    }
};

It throws the error object from error.request and error.response is undefined since it is empty. So, I assume it might be some error with some instructions in dockerfile? or need more configuration? (please guide me)

Belows are dockerfiles lies in my front/backend:

# Build the express app
FROM node:20 AS build

# Set the working directory inside the container
WORKDIR /booking-express

# Copy package.json and package-lock.json (or yarn.lock)
COPY package*.json ./

# Install dependencies (including development dependencies)
RUN npm install

# Copy the rest of the application code
COPY . .

# Production
FROM node:20-alpine

# Set the working directory inside the container
WORKDIR /booking-express

# Copy only the necessary files from the build stage
COPY --from=build /booking-express /booking-express

# Install only production dependencies
RUN npm install

# Expose the port the app runs on
EXPOSE 4000

# Define the command to run the application
CMD ["node", "./api/index.js"]

# Build the React app
FROM node:20 AS build

# Set the working directory inside the container
WORKDIR /booking-react

# Copy the package.json and package-lock.json files
COPY package*.json ./

# Install dependencies
RUN npm install

# Copy the rest of the application files
COPY . .

# Build the app
RUN npm run build

# Serve the built files with Nginx
FROM nginx:alpine

# Copy the build files to the Nginx directory
COPY --from=build /booking-react/build /usr/share/nginx/html

# Expose port 80    
EXPOSE 80

# Start Nginx
CMD ["nginx", "-g", "daemon off;"]

I use docker build to build from the instructions. To run containers I just use command: docker run -p 4000:4000 --env-file .env booking-express and docker run -p 80:80 --env-file .env booking-react without docker-compose.yaml because I’m really new to docker. The env is also included in container as I checked with docker -it I have MySQL as a database and it seems to have a problem connection to it during API request.

I’d like to check some log in the backend, but the only thing it shows is payload (I also have no clue why I see it. It shows in backend when I run backend container) because it seems like the connection is refused by server or something. I can see log in container:

Server is running on port 4000
username:  test-user
{
  user_id: 1,
  password: 'hashed pw'
}

It displays username: test-user before the code would used to typically execute pool.query() (to connect to MySQL DB). I just want to know why there is no response coming back.

Is there a way I can change certain values in files when I `build` my React project?

I am working on a Create React App project where I am slowly replacing components on a large site with React ones. Since this is an ongoing project, some supporting files are still being developed locally and have not been deployed yet (though there are older versions of the files I can use).

I was wondering if upon running npm run build it would be possible to modify some parts of my files.

For example, in an Icons atom level component it would be great to change

import Svgs from '../../../svgs/icons-main.svg';

which is still being developed, to:

import Svgs from 'https://www.example.com/media/svgs/icons-main.svg';

which is on the live site that the component will be deployed to.

Is there some way to say

“when npm run build is run change '../../../svgs/icons-main.svg' to 'https://www.example.com/media/svgs/icons-main.svg'

or something similar?

can a js URL object be a long number?

new URL(`http://12345678901`) is not valid but new URL(`http://1234567890`) and new URL(`http://a12345678901`) are.

try logging new URL(`http://12345678901`)

//these work
console.log(new URL(`http://1234567890`))
console.log(new URL(`http://a12345678901`))

Here’s the error in chrome:

VM2064:1 Uncaught TypeError: Failed to construct ‘URL’: Invalid URL at :1:1 (anonymous) @ VM2064:1

Firefox:

Uncaught TypeError: URL constructor: http://12345678901234567890:5000 is not a valid URL.
debugger eval code:1
debugger eval code:1:1
debugger eval code:1

I expect the url to work. I tried reading https://url.spec.whatwg.org/#concept-basic-url-parser but it’s very dense and I don’t really understand it.

JavaScript / Google Apps Script – Using multiple URLS to fetch API JSON Data

I’m currently trying to program a bit of code in Google Apps Script that catalogues item pricing data for an MMORPG by connecting to an API. I’ve managed to cobble up some code (shown below) that successfully does this for a single item, but I’ve hit a roadblock with getting it to work for a range of cells in order to cover every item on the spreadsheet.

Essentially, what I need this to do, is grab a series of itemIDs in a defined range (ie. D8:D24), query the API for each of those entries by appending each itemID into the URL, and then properly display it in the adjacent “F” column for each item.

Admittedly I’ve never coded with JavaScript before and even getting this far took me some learnin’. I think what I might need is a Promise.all() to query the API multiple times and put those results in an array, but I have no clue how to go about that and adapt that to my existing code.

Any help with this would be greatly appreciated. Thank you.

function getPrices() {
  
  const url = "https://universalis.app/api/v2/world/"

  if (SpreadsheetApp.getActiveSheet().getName() == 'Boss Weapons') {
    let sheet = SpreadsheetApp.getActiveSheet();
    let itemID = [];
    itemID.push(sheet.getRange('D8').getValue());

    let request = url + itemID + "?listings=0&entries=0"
    let response = UrlFetchApp.fetch(request);
    let data = JSON.parse(response.getContentText());

    let itemData = [];
    itemData.push(data.minPrice); 
  
    let item = [];
    item.push(itemData);

    let targetRange = sheet.getRange('F8');
    targetRange.setValue(item);
  }
}

js Promise memory leak

I tried to prevent the interface response in the axios request interception function,
but I suspect this approach will cause memory leaks

Why is there no reference to data in the finally function?
Why is the data memory released?

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
<button onclick="handleClick()">Click</button>
</body>
<script>
  const task = (data) => {
    // console.log(1)
    new Promise((resolve, reject) => {
      // console.log(2)
      resolve();
    }).then(() => {
      // console.log(4)
      return new Promise(() => {
      })
    }).finally(() => {
      console.log("finally");
      console.log(data);
    })
    // console.log(3)
  }

  function test() {
    return Array(1000000).fill(new Date().toUTCString() + "1212121212121212");
  }

  window.onload = function () {
  }
  const handleClick = () => {
    console.log("click ");
    const data = test();
    task(data);
  }


</script>
</html>

Dynamically growing data structure in javascript(like java arraylist)

I have a usecase wherein I am reading streaming data from server, and putting it into an array. So my approach is:

var points = str.split("n"); //split input based on new line character
var positions = new Float32Array();
for (let i = 0; i < points.length; i++) {
  var coords = points[i].split("_"); //split line into individual values separated by '_'
  for(let j=0; j < coords.length; j++) {
      var coord = parseFloat(coords[j]) // parse string to float
      positions.push(coord); // add to float array
  }
}

But this is not working. code execution just stops at ‘push’, and nothing happens after that.

Is Float32Array not correct data structure for this usecase?

Scroll animation javascript

const boxes = document.querySelectorAll(".decSquare5")
window.addEventListener("scroll", () => {
  const innerHeightOfWindow = window.innerHeight;

  boxes.forEach(box => {
    const boxTop = box.getBoundingClientRect().top

    if (boxTop < innerHeightOfWindow) {
      box.classList.add("show")
    } else {
      box.classList.remove("show")
    }
  })
})
.decSquare5 {
  height: 250px;
  width: 4%;
  border: none;
  background-color: #9b9b9b;
  opacity: 0.3;
  position: relative;
  z-index: 2;
  top: 300px;
  left: 1%;
  margin-top: -250px;
  transform: translateX(400%);
  transition: 0.5s;
}

.decSquare5.show {
  transform: translateX(0);
}

I watched a tutorial on how to do a scrolling animation and that guy had a lot of divs with the class=box, now i just want this for 1 div(decSquare5) but it doesnt work.I think the class is not getting the .show class but i dont know how to fix it.

Is it reasonable to tackle making a large react project for the front end even if i do not know javascript? [closed]

I have experience with html and css and can make a relatively nice responsive website. I have not experemented with javascript besides copying tutorials but I do understannd the logic of it all for the most part. I know react is used in many modern front ends and was wondering if it is too ambitious to learn it to create this large project.

I also considered using this video as a guide: https://www.youtube.com/watch?v=_W3R2VwRyF4

Thanks in advance for any helping remarks.

Issues with my player and enemy not being drawn on to the canvas, any ideas?

This is the only issue im having currently with my scripts, im not sure if its the drawing order but ive tried to rearrange my drawing. If y’all can help me so that I can fix this issue that would be greatly appreciated .


function gameloop() {
  // Clear the canvas
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Draw background elements
// Set timeout to hide symbols after 5 seconds
  bg.draw();
  cloudBig.update(ctx);
  cloudBig2.update(ctx);

  backgroundLevel1.draw();

  water.draw();
  waterSmall.draw();
  waterSmallTwo.draw();
  palmTree.draw();
  palmTree2.draw();
  palmTreeSide.draw();
  palmTreeSide2.draw();

  // Draw the p1Symbol

  playerUpdate();
  p1Symbol.draw(); // Update game objects
  p1Symbolp.draw(); // Update game objects

  // p1update();
  // p1pupdate();
  p2Symbol.draw(); // Update game objects
  p2Symbolp.draw(); // Update game objects

  




  enemy.enemyMovement();
  player.movement();

  // Update hurtboxes
  player.updateHurtbox();
  enemy.updateHurtbox();

  // Draw game objects
  player.update();
  player.draw();
  enemy.update();
  enemy.draw();

  // Check collisions
  attackCollision();
  enemyAttackCollision();
  // CollisionBlocks.forEach(block => {
  //   block.draw();
  // });

  // Request the next frame
  window.requestAnimationFrame(gameloop);
}

// Start the game loop
gameloop();

I mentioned that ive tried rearranging my drawings. So not sure what’s causing this issue.