All of my a href https link in html code won’t open, I think Barba JS is the culprit but I’m not sure [closed]

I’ve made my website portfolio and it works fine a few months ago… and suddenly all of my external links won’t open, you guys can check it here: https://hafidyusuf.com/

there is no problem for every link to the own website page, but every link that goes outside of the website won’t work, can you help me on this please, thanks

I wanted my https link to be open like it should

How to check if a chrome tab is an installed Desktop App/Shortcut?

I’m building a browser extension, and I want to distinguish between users’ regular tabs and installed apps/shortcuts. How do I check the difference?

I looked at the chrome.tabs API and found nothing to help me. If I go to the browser’s task manager I see that it shows the difference. Regular tab processes have the “Tab” name while installed shortcuts have the “App” name.

Iterate element inside html div element

I am not familiar with javascript and facing this weird situation.
I am using javascript to iterate over div element and retrieve href values from all <a> element inside, the purpose is to handle click on <a> element by JavaScript instead of default by HTML.

The iteration works but all links target replaced to the last <a> href values.

$(document).ready(function() {
  //NavMenu();
  //NavActive();
  NavClick();
  console.log('tes');
});

function NavClick() {
  var nav_item = document.getElementById('nav-menu').querySelectorAll('div')
  for (let i = 0; i < nav_item.length; i++) {
    item = nav_item[i].querySelector('a').getAttribute('href')
    nav_item[i].addEventListener('click', function(e) {
      e.preventDefault();
      $.ajax({
        url: item,
        contentType: 'application/json',
        dataType: 'json',
        success: function(data) {
          $('title').html(data.title)
          window.history.replaceState({}, '', item)
          $('#content').html(data.data)
        }
      });
    });
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="row col-12 justify-content-end" id="nav-menu">
  <div class="col-auto">
    <a href="/" class="px-1">
            Short
        </a>
  </div>
  <div class="col-auto">
    <a href="/myurl/' %}" class="px-1">
            My URL
        </a>
  </div>
  <div class="col-auto">
    <a href="/group/" class="px-1">
            My Collection
        </a>
  </div>
  <div class="col-auto">
    <a href="/group/create/" class="px-1">
            New Collection
        </a>
  </div>
</div>

What I expecting is my code will add event listener to each element and retrieve the “href” value so I can send request to server with the url.

eg. when I click this link, javascripts will send request to 127.0.0.1 but what i get is request send to 127.0.0.1/group/create/.

<div class="col-auto">
    <a href="/" class="px-1">
        Short
    </a>
</div>

is my logics wrong or I miss something on my codes?

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(~~);
     }
  }
});

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);
  }
}