WordPress shortcode with JS

I am working on a wordpress project and I’m completely stuck on something … I have to put somewhere near the post (in a post grid page) the reading time of them. So I got to test laking a js script that take the url (href found on a element) and a function in the function.php file of my theme that take the url of a post and return the calculated reading time… Though, it work when I put manually the shortcode, but not when I’m using JS.
(BTW, I’m using elmentor as well …)

JS script (html block):

<script>
document.addEventListener('DOMContentLoaded', function(){
    let childDivs = document.querySelectorAll('.void-row > *');
    childDivs.forEach(child =>{
        let links = child.querySelectorAll('a');
        let postUrl = links[0].href;
        let short = `[get_post_reading_time url=${postUrl}]`;
        links[4].textContent = short;
    });
});
</script>

Php Function (function.php):

function get_post_reading_time($att = '', $content = null){
    $url = $att['url'];
    $post_id = url_to_postid($url);
    $post = get_post($post_id);
    $content = $post->post_content;
    $word_count = str_word_count(strip_tags($content));
    return ceil($word_count / 200);
}

add_shortcode('get_post_reading_time', 'get_post_reading_time');

Could someone help me understand and/or find another way to do that? Thanks in advance.
(Maybe it’s because function.php replace the shortcode in the JS script before it is inside the textContent of the links[4] ?)

Node.js FilePath

I try to get file from form and send it to the “/public” directory but code
do not recognize filepath. I used “formidable” library. The file path is always undefined.
If you have any idea how i can repair this please answer

This is the result:

oldPath: undefined
Invalid file path: undefined

This is the code:

let http = require("http");
let formidable = require("formidable");
let fs = require("fs");

let htmlform = 
`<!DOCTYPE html>
<html>
<head><title>file upload</title></head>
<body>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file1"> <br>
        <input type="submit" value="Send">
    </form>
</body>
</html>`;


http.createServer(
    function(req, res){
        if(req.url === "/upload") {
            let form = new formidable.IncomingForm();
            form.parse(req, function(err, fields, files){
              console.log( JSON.stringify(files.file1));
              let oldPath = files.file1.name;
              let newPath = './public/' + files.file1.name;
              console.log('oldPath:', oldPath);
              if(typeof oldPath == 'string' && oldPath.length > 0) { 
                fs.rename(oldPath, newPath, function(err){
                  if(err) {
                    console.error('fs.rename error:', err);  // Log the error
                    res.write('File upload failed!');
                  } else {
                    res.write('File uploaded and moved!');
                  }
                  res.end();
                });
              } else {
                console.error('Invalid file path:', oldPath);  // Log the error
                res.write('File upload failed!');
                res.end();
              }
            });
        } else {
            res.writeHead(200, {"Content-type": "text/html"});
            res.end(htmlform);
        }
    }

).listen(8080);

My splash screen doesn’t appear when launching my Next.js PWA on ios

My splash screen doesn’t appear when launching i’m launching my app.
I only see a white screen when launching the app.

I tried changing Next Metadata object like this and I rebuild the PWA app many time:

appleWebApp: {
    title: `Apple ${APP_DEFAULT_TITLE}`,
    capable: true,
    statusBarStyle: "black-translucent",
    startupImage: "/splash_screens/icon.png"
  }

Here the start of my manifest.json:

"id": "/",
  "name": "Instamint",
  "theme_color": "#FFFFFF",
  "background_color": "#FFFFFF",
  "start_url": "/",
  "display": "standalone",
  "orientation": "portrait"

No routes matched location “/new” [closed]

Sempre começo a linkar o front de uma página com a api aparece esse erro com o nome da página, como por exemplo nessa “/new”.

Arquivo .jxs
enter image description here
enter image description here

Rotas do app
enter image description here

API: https://github.com/VagnerNatvidade/api-rocketseat
Front-end: https://github.com/VagnerNatvidade/rocketnotes

Consegui solucionar o da página de profile colocando chaves entre os parâmetros de umas das callbacks dentro da função, mas na página new não to conseguindo

Three JS shadows not showing?

i have made a interactive 3d model on my website with Threejs, and everything work other than shadows, i cant make shadows work, i am new to three js so it could be i am skiping some important part.

Here is my JS code:

import * as THREE from "https://cdn.skypack.dev/[email protected]/build/three.module.js";
import { OrbitControls } from "https://cdn.skypack.dev/[email protected]/examples/jsm/controls/OrbitControls.js";
import { GLTFLoader } from "https://cdn.skypack.dev/[email protected]/examples/jsm/loaders/GLTFLoader.js";

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

let mouseX = window.innerWidth / 2;
let mouseY = window.innerHeight / 2;
let object;
let controls;
let objToRender = 'dino';

const renderer = new THREE.WebGLRenderer({ alpha: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.getElementById("container3D").appendChild(renderer.domElement);

camera.position.z = objToRender === "dino" ? 4 : 500;

const topLight = new THREE.DirectionalLight(0xffffff, 3); 
topLight.position.set(-1.05307, 0.107503 , 4.52525 );
topLight.castShadow = true;
scene.add(topLight);

const ambientLight = new THREE.AmbientLight(0xFFFFFF, objToRender === "dino" ? 1 : 1);
scene.add(ambientLight);

renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap; 

const loader = new GLTFLoader();

loader.load(
    `models/${objToRender}/scene.gltf`,
    function (gltf) {
        object = gltf.scene;
        object.castShadow = true; 
        object.receiveShadow = true; 
        scene.add(object);
        animate(); 
    },
    function (xhr) {
        const percentage = (xhr.loaded / xhr.total * 100).toFixed(2);
        console.log(percentage + '% loaded');
        // Show loading progress somewhere in your UI
        document.getElementById("loadingProgress").innerText = `Loading: ${percentage}%`;
    },
    function (error) {
        console.error(error);
    }
);

if (objToRender === "dino") {
    controls = new OrbitControls(camera, renderer.domElement);
}

function animate() {
    requestAnimationFrame(animate);
    if (object && objToRender === "eye") {
        object.rotation.y = -3 + mouseX / window.innerWidth * 3;
        object.rotation.x = -1.2 + mouseY * 2.5 / window.innerHeight;
    }
    renderer.render(scene, camera);
}

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

document.onmousemove = (e) => {
    mouseX = e.clientX;
    mouseY = e.clientY;
};

And here is picture from my website:
enter image description here

I tried asking chatgpt for help , but he only gave me fixes that didnt work.

How to plot functions with asymptotic behavior like tan(x), ln(x), and log(x) in JavaScript?

I’m working on a project where I need to plot graphs of mathematical functions in JavaScript, specifically functions that exhibit asymptotic behavior or approach infinity at certain points, such as tan(x), ln(x), and log(x). I’m struggling with how to accurately represent these functions, especially near the points where they approach infinity (for example, near vertical asymptotes for tan(x)).

This is my Code to draw functions:

export function drawFunction(latexStr) {
  let isTan;
  // Draw function
  console.log(canvas.height);
  console.log(canvas.width);

  let prevY; // Stores the previous Y value
  let startY = true; // To know when a new line is needed

  ctx.beginPath();
  ctx.strokeStyle = "blue";
  ctx.lineWidth = 2;
  // Draw the function in small steps
  for (let x = -canvas.width / 2; x <= canvas.width / 2; x += stepSize) {
    let y = parser(latexStr, x)[0]; // f(x)
    isTan = parser(latexStr, x)[1];
    console.log(isTan);
    // Skip drawing the graph if it's infinite or too large for the canvas
    if (Math.abs(y) > canvas.height / scaleFactor && !isTan) {
      startY = true;
      y = (y < 0 ? -1 : 1) * (canvas.height / scaleFactor - 1);
    }

    const adjustedX = canvas.width / 2 + x * scaleFactor; // Calculation of the small X line
    const adjustedY = canvas.height / 2 - y * scaleFactor; // Calculation of the small Y line

    /*     if (Math.round(x * 100) / 100 === stepSize)
      ctx.moveTo(adjustedX, adjustedY); */

    // Draw or move to position
    if (startY) {
      ctx.moveTo(adjustedX, adjustedY);
      startY = false;
    } else {
      if (prevY !== undefined && Math.abs(y - prevY) > 1 * scaleFactor) {
        if (isTan) {
          ctx.stroke(); // Draw the current line
          ctx.beginPath(); // Start a new line
          ctx.moveTo(adjustedX, y < 0 ? canvas.height : 0); // Move to the edge of the canvas
        } else {
          ctx.moveTo(adjustedX, adjustedY); // Move to the new starting position
        }
      } else {
        ctx.lineTo(adjustedX, adjustedY);
      }
    }

    prevY = y;
    //console.log(Math.round(x * 100) / 100);
  }

  ctx.stroke(); // Draw the function
}

Drawing a normal function like “y = x+2” is no problem, but issues arise with a function like “y = tan(x)” as seen in the image below:

Image of the tan(x) Function

The values are correct, so it seems not to be an issue with the calculations but rather with the way the drawing is handled. I’ve searched everywhere but couldn’t find a solution. Does anyone have suggestions on how I could improve the drawing algorithm to better handle infinity points for functions like tan(x)?

Thank you in advance for your help!

Using StackBlitz, and for some unholy reason the main.tsx it gave has an error where it wasn’t loading the app.tsx correctly

Ok, i’ll give you all the code here, ’cause ive got no idea whats going on here. No idea how to fix it, because config files are fucking black magic from the dark wizards of Arrakornesol.

I didn’t touch anything here because i am terrified of making a mistake here and ruining the code, and if i do i’ll have to read all the documentation relating to main.tsx configs, and hell knows i am NOT doing that yet. All i know, is the IDE is yelling at me for blasphemy and its not loading the app.tsx correctly.

Here it is:

import React from 'react'
import ReactDOM from 'react-dom/client'
// this './app.tsx' is where the error is coming from
import App from './App.tsx' 
import './index.css'

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
)

P.S. I posted a different problem a half hour ago about the App.tsx throwing an error before noticing this.

Why does my ‘includes’ statement require the entire string?

I am trying to use an ‘if includes’ statement within my Node JS project to filter the results pulled from a .txt file. The idea is that the serial number a user inputs correlates to specific models from the first 5 numbers so I would like to filter the data that gets put into my HTML <select> however it seems to only work if the entire string is identical. Perhaps I’m wrong (I’m very new to JS so I very well could be) but it’s my understanding that .includes should be ‘if X contains Y’ and not ‘if X = Y’. I have used it elsewhere in my project with text inputs and it does not behave this way.

function PopulateModelList() {
    const fs = require("fs");
    const { parse } = require("csv-parse");

    var modellist = document.getElementById('model');
    var serial = document.getElementById("serialnumberinput").value; //I have tried without .value also
    var serialmodel = serial.substring(0,5); //Adding .value to this results in 'undefined'

    var testing = document.getElementById("modeltesting");
    testing.innerHTML += serialmodel; //Outputs '19180'

    fs.createReadStream("./model.txt") //Tried using it as a .csv also but it did not change anything
    .pipe(parse({
        delimiter: ",",
        from_line: 1,
    }))

    .on("data", function(row) {
        console.log(row);
        
        if (row.includes(serialmodel)) {
            modellist.innerHTML += '<option value="' + row + '">' + row + '</option>' ;
        }

        else {

        }
    })
}

My ‘serialmodel’ var outputs ‘19180’ and the line this should call from .txt file is ‘19180 – Testing’. If I change my HTML to allow text input and type the full line ‘19180 – Testing’ into the ‘serialnumberinput’ field then the function works as intended so it seems to be require the entire string to match. I have tried using indexOf instead however this just outputs the entire file. I’ve tried a number of other workarounds I found from other forum posts too however I’m picking this project back up after a hiatus so cannot remember what exactly those were, apologies.

Popups obscured by other tag

I’m trying to do popup success when the customer makes an order. I get the Popup on the internet here the link https://codepen.io/fullstacksagarofficial/pen/mdjKgxW . But when I put in my code, I change the event in JavaScript is my add to cart button event whenever customer add to cart success. But the problem is the Popup obscured by another elements in view like this popup when add to cart success. I can’t even click the close button to close the Popup, I have to scroll down like this img to see entire a popup and click the close button. Here the css :

/* Google Fonts - Poppins */
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&display=swap");

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;

}

section {
    position: fixed;
    height: 100%;
    width: 100%;
    background: #e3f2fd;
}

button {
    font-size: 18px;
    font-weight: 400;
    color: #fff;
    padding: 14px 22px;
    border: none;
    background: #4070f4;
    border-radius: 6px;
    cursor: pointer;
}

    button:hover {
        background-color: #265df2;
    }

    button.show-modal,
    .modal-box {
        position: fixed;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
    }

section.active .show-modal {
    display: none;
}

.overlay {
    position: fixed;
    height: 100%;
    width: 100%;
    background: rgba(0, 0, 0, 0.3);
    opacity: 0;
    pointer-events: none;
}

section.active .overlay {
    opacity: 1;
    pointer-events: auto;
}

.modal-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    max-width: 380px;
    width: 100%;
    padding: 30px 20px;
    border-radius: 24px;
    background-color: #fff;
    opacity: 0;
    pointer-events: none;
    transition: all 0.3s ease;
    transform: translate(-50%, -50%) scale(1.2);
}

section.active .modal-box {
    opacity: 1;
    pointer-events: auto;
    transform: translate(-50%, -50%) scale(1);
}

.modal-box i {
    font-size: 70px;
    color: #75d479;
}

.modal-box h2 {
    margin-top: 20px;
    font-size: 25px;
    font-weight: 500;
    color: #333;
}

.modal-box h3 {
    font-size: 16px;
    font-weight: 400;
    color: #333;
    text-align: center;
}

.modal-box .buttons {
    margin-top: 25px;
}

.modal-box button {
    font-size: 14px;
    padding: 6px 12px;
    margin: 0 10px;
}
I have changed many attributes in css file in many ways. But still doesn't work. I think maybe because the modal box is transparent. Anyone know the problem cause the obscured. I really appreciate any instructions. Thanks you

React native – Restart background and foreground task after the device stopped it for memory/battery saving

I’m creating my first React Native mobile app. The app gets the locations for tracking journeys in a foreground task.

Sometimes my (android) devices stops this task for (I think) memory saving purposes. How can I make sure task either never is stopped or starts after there is memory available?

I was looking to check and update the status of the foreground task in the event broadcast Intent.ACTION_BATTERY_CHANGED. But i’m not sure if this is possible when the app is closed or not active in the background.

Javascript Function Works In a Testing Script, But Not In Actual App

The below function (with debugging comments included) works exactly as expected in a testing script, but when used in the actual app it doesn’t work.

Function in question:

function getEnvelopeById(id) { //returns object if found, undefined if not
    console.log("nEntered function getEnvelopeByIdn");
    console.log("paramenter: id: " + id);
    console.log("nenvelopesArray: ");
    console.log(envelopesArray);
    const e = envelopesArray.find((element) => element.Id === id);
    console.log("nRan array method evelopesArray.findnResult returned: ");
    console.log(e);
    return e;
}

Below is the testing script where it works.

let envelopesArray = [];


class Envelope {
    
    static _idCounter = 0;
    
    constructor(title="default", budget=100) {
        this._id = ++Envelope._idCounter;
        this._title = String(title);
        if(typeof budget === "number") { this._budget = budget; }
            else { this._budget = 100; }
    }
    get Id() { return this._id; }
    
    get Title() { return this._title; }
    set Title(t) { this._title = t; }
    
    get Budget() { return this._budget; }
    set Budget(a) { this._budget = a; }

    add(amount) { this._budget += amount; }
    
    subtract(amount) { this._budget -= amount; }
    
    static getId() { return Envelope._idCounter; }
}  //class Envelope

function getEnvelopeById(id) { //returns object if found, undefined if not
    console.log("nEntered function getEnvelopeByIdn");
    console.log("paramenter: id: " + id);
    console.log("nenvelopesArray: ");
    console.log(envelopesArray);
    const e = envelopesArray.find((element) => element.Id === id);
    console.log("nRan array method evelopesArray.findnResult returned: ");
    console.log(e);
    return e;
}

function createEnvelope(obj) {
    let newEnvelope = new Envelope(obj.title, obj.budget);
    if(newEnvelope) { envelopesArray.push(newEnvelope); }
    return newEnvelope;
}

createEnvelope({
    title: "first",
    budget: 100
});
createEnvelope({
    title: "second",
    budget: 200
});


const e = getEnvelopeById(1);
console.log(e);

Working output to console:


Entered function getEnvelopeById

paramenter: id: 1

envelopesArray:
[
  Envelope { _id: 1, _title: 'first', _budget: 100 },
  Envelope { _id: 2, _title: 'second', _budget: 200 }
]

Ran array method evelopesArray.find
Result returned:
Envelope { _id: 1, _title: 'first', _budget: 100 }
Envelope { _id: 1, _title: 'first', _budget: 100 }

App script where function no longer works (only necessary portions included):

let envelopesArray = [];


class Envelope {
    
    static _idCounter = 0;
    
    constructor(title="default", budget=100) {
        this._id = ++Envelope._idCounter;
        this._title = String(title);
        if(typeof budget === "number") { this._budget = budget; }
            else { this._budget = 100.00; }
    }
    get Id() { return this._id; }
    
    get Title() { return this._title; }
    set Title(t) { this._title = t; }
    
    get Budget() { return this._budget; }
    set Budget(a) { this._budget = a; }

    add(amount) { this._budget += amount; }
    
    subtract(amount) { this._budget -= amount; }
    
    static getId() { return Envelope._idCounter; }
}  //class Envelope

function getEnvelopeById(id) { //returns object if found, undefined if not
    console.log("nEntered function getEnvelopeByIdn");
    console.log("paramenter: id: " + id);
    console.log("nenvelopesArray: ");
    console.log(envelopesArray);
    const e = envelopesArray.find((element) => element.Id === id);
    console.log("nRan array method evelopesArray.findnResult returned: ");
    console.log(e);
    return e;
}

//testing purposes only//

createEnvelope({
    title: "first",
    budget: 100
});
createEnvelope({
    title: "second",
    budget: 200
});


console.log("Created test envelopes.nnenvelopesArray:");
console.log(envelopesArray);
console.log('n');


//end of testing area//

envelopesRouter.param("id", (req, res, next, id) => {
    const found = getEnvelopeById(id);
    if(found) {
        req.envelope = found;
        next();
    } else {
        res.status(404).send({message: `Could not find envelope with the ID ${id}`});
    }
});

When the param endpoint calls the function, the console logging shows that it is returning undefined instead of the object as it does in the working test script.

Because the function works as expected in the test script, returning the object with the matching ID (_id), I am unsure what to change to make it work in the actual script where it only returns undefined.

Why I am not able navigate to HomeScreen after displaying Text for 2 seconds in React Native?

So, I am trying display HomeScreen after displaying a Text “Hello App” initially when I open the App. It should display the Text “Hello App” for 2 seconds and then display HomeScreen. Below is the code

App.js

import React, {useEffect, useState} from 'react';
import {Image, View, StyleSheet, Text} from 'react-native';
import * as SplashScreen from 'react-native-splash-screen';
import HomeScreen from './src/HomeScreen';

const SplashScreenComponent = ({navigation}) => {
const [isVisible, setIsVisible] = useState(true);
useEffect(() => {
const hideSplash = async () => {
  await SplashScreen.hide(); // Hide the splash screen after 2 seconds
  setIsVisible(false);
  navigation.navigate(HomeScreen);
};

const timeoutId = setTimeout(hideSplash, 2000); // Delay for 2 seconds

return () => clearTimeout(timeoutId); // Clear timeout on component unmount 
}, [navigation]);

return (
isVisible && (
  <View style={styles.container}>
    <Text>Hello App</Text>
  </View>
));};

const styles = StyleSheet.create({

container: {
flex: 1,
justifyContent: ‘center’,
alignItems: ‘center’,
backgroundColor: ‘white’, // Optional background color
},
image: {
width: ‘100%’,
height: ‘100%’,
resizeMode: ‘cover’, // Adjust resize mode as needed
},});
export default SplashScreenComponent;

This is the code of my HomeScreen.js

import React from 'react';
import {View, Text, StyleSheet} from 'react-native';

const HomeScreen = () => {
return (
<View style={styles.container}>
  <Text>Welcome to Home Screen!</Text>
</View> 
);};

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},});

export default HomeScreen;`

I have created a HomeScreen and imported it in App.js and put it as an argument in navigation.navigate(HomeScreen). This is the errorenter image description here that I am displaying

The problem with the adaptive slider in pure JavaScript

I needed a slider in pure JavaScript and I used the code below, but modified it for my project. If something is named strangely, then don’t pay attention to it, I cut it out of my project and simplified it. The problem is that when dragging objects on the computer, everything works fine. But on the phone or in adaptive layout mode, objects move incorrectly. I’ve used different ways to initialize tapping on the phone and this is the simplest of them, but they all work the same way.

I checked the events of dragging and finding the inside of the container, but it didn’t help me.

const containerMass = 5;
const mouseMass = 10;

let imageHasLoaded = false;

let mouseX = 0;
let prevMouseX = 0;
let mouseXOnDown = null;
let isMouseDown = false;

let containerPosition = 0;
let mouseVelocity = 0;
let containerVelocity = 0;

let imagesElement = null;

const createBeltScroller = (container, images) => {
  imageHasLoaded = true;
  const beltDOMItems = images.map((image, index) => {
    const element = document.createElement("div");
    element.classList.add("item");
    const elementDiv = document.createElement("div");
    elementDiv.style.height = "200px";
    elementDiv.style.width = "200px";
    elementDiv.style.backgroundColor = 'green'
    elementDiv.innerHTML = image
    element.appendChild(elementDiv);
    return element;
  });
  imagesElement = beltDOMItems.map((element) => element);
  beltDOMItems.forEach((beltDOMItem) => {
    container.appendChild(beltDOMItem);
  });
};
const container = document.querySelector(".container");

createBeltScroller(container, ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]);

// Mouse event handlers
const onMouseUpdate = (event) => {
  mouseX = event.pageX;
}; // Mouse movement
const onMouseDown = () => {
  isMouseDown = true;
}; // Mouse button press
const onMouseUp = () => {
  isMouseDown = false;
}; // Mouse button release

// Add pointer event listeners
document.addEventListener("pointermove", onMouseUpdate, false);
document.getElementById("container").addEventListener("pointerdown", onMouseDown);
document.addEventListener("pointerup", onMouseUp);

const calculateMouseMomentum = () => {
  if (isMouseDown) {
    if (mouseXOnDown == null) {
      mouseXOnDown = mouseX;
      containerVelocity = 0;
    }
    const distance = mouseX - mouseXOnDown;
    mouseVelocity = mouseX - prevMouseX;
  } else {
    if (mouseXOnDown != null) {
      containerVelocity =
        ((2 * mouseMass) / (mouseMass + containerMass)) * mouseVelocity +
        ((containerMass - mouseMass) / (mouseMass + containerMass)) *
        containerVelocity;

      const maxVelocity = 60;

      if (containerVelocity > maxVelocity) {
        containerVelocity = maxVelocity;
      } else if (containerVelocity < -maxVelocity) {
        containerVelocity = -maxVelocity;
      }

      mouseXOnDown = null;
      mouseVelocity = 0;
    }
  }

  prevMouseX = mouseX;
};

const updateContainer = () => {
  const boundRight = -container.offsetWidth + window.innerWidth - 85;

  const isOutBound =
    containerPosition > 0 || containerPosition < boundRight;

  if (!isMouseDown) {
    const mu = 0.04;
    const g = 10;
    const flictionForce = containerMass * g * mu;
    const flictionA = flictionForce / containerMass;

    if (containerVelocity > 0) {
      containerVelocity -= flictionA;
      if (containerVelocity < 0) {
        containerVelocity = 0;
      }
    } else if (containerVelocity < 0) {
      containerVelocity += flictionA;
      if (containerVelocity > 0) {
        containerVelocity = 0;
      }
    }

    if (isOutBound) {
      const k = 0.01;
      const restLength = containerPosition > 0 ? 0 : boundRight;
      const currentLength = containerPosition;
      const dragForce = 1 * k * (restLength - currentLength);

      const dragForceA = dragForce / containerMass;
      containerVelocity += dragForce;

      const nextPosition = containerPosition + containerVelocity;

      if (containerPosition < boundRight && nextPosition > boundRight) {
        containerVelocity = 0;
        containerPosition = boundRight;
      } else if (containerPosition > 0 && nextPosition < 0) {
        containerVelocity = 0;
        containerPosition = 0;
      }
    }
  }

  containerPosition = containerPosition + containerVelocity + (isOutBound ? mouseVelocity / 2 : mouseVelocity);
  container.style.transform = `translate(${containerPosition}px)`;
};

const loop = () => {
  calculateMouseMomentum();
  updateContainer();
  window.requestAnimationFrame(() => {
    loop();
  });
};

loop();
.container {
  height: fit-content;
  display: inline-flex;
  flex-wrap: nowrap;
  align-items: center;
  touch-action: pan-y;
  user-select: none;
  cursor: grab;
  margin: 2% 0;
  font-size: 150px;
}

.item {
  width: fit-content;
  height: fit-content;
  padding-left: 4.43vw;
  opacity: 1;
  transition: opacity 2s;
}
<div id="container" class="container"></div>