Slide carousel on click, snap to center

I’m trying to make a carousel slide with images, I want it to be able to slide to the next and prev image on click, and I need to snap each image/slide to the center of the window. But each image has varying widths, how can I achieve this? Perhaps with gsap?

Currently the slides in this code snippet have the same width but I will be using images of varying widths in my actual project.

.scroll-container {
    position: absolute;
    overflow-y: hidden;
    white-space: nowrap;
    background: transparent;
    height: 100vh;
    width: 100vw;
    margin-right: 0;
    border: 4px solid pink;
    display: flex;
}

.gridscroll {
    display: flex;
    height: 100%;
    border: 2px solid yellow;
}

.project-sections {
  height: 100%;
  width:  600px;
  background-color:green;
  border: 2px solid blue;
}


#scroll-right {
  position: fixed;
  /* width: 49vw;
  height: 94vh; */
  width: 60px;
  height: 60px;
  right:0;
  cursor: grab;
  background-color: red;
}
#scroll-left {
  position: fixed;
  /* width: 49vw;
  height: 94vh; */
  width: 60px;
  height: 60px;
  left:0;
  cursor: grab;
  background-color: red;
}
<div class="scroll-container">
  <div class="gridscroll">
    <div class="project-sections">
      <img src="" />
    </div>
    <div class="project-sections">
      <img src="" />
    </div>
    <div class="project-sections">
      <img src="" />
    </div>
    <div class="project-sections">
      <img src="" />
    </div>
    <div class="project-sections">
      <img src="" />
    </div>
    <div class="project-sections">
      <img src="" />
    </div>
    <div class="project-sections">
      <img src="" />
    </div>
    
    <div id="scroll-right"></div>
    <div id="scroll-left"></div>
  </div>
</div>

Discord create temporary channel by slash command

Hey i hope is everything okey with you reader i was trying to do a command to my discord bot that when i do /channel1 will create automatic a voice channel call channel1

if (commandName === 'channel1') {
    // Your logic for creating a temporary voice channel
    const temporaryChannelName = 'Temporary Channel'; // You can customize the channel name
    console.log('Temporary Channel Name:', temporaryChannelName);

    try {
      const channel = await interaction.guild.channels.create(temporaryChannelName, {
        type: 'GUILD_VOICE',
        name: `${temporaryChannelName}`, // Use template literal for string interpolation
      });

      // Move the user to the newly created channel
      await interaction.member.voice.setChannel(channel);
    } catch (error) {
      console.error('Error creating temporary channel:', error);
      interaction.reply('Unable to create a temporary channel at the moment.');
    }
  }
});

is giving DiscordAPIError[50035] Invalid body

if you have any aswer to me and help me i will thank you 🙂

when i do /channel1 will create automatic a voice channel call channel1

Why does this function returns 4 and not 3? (javascript)

This is the function and it’s role it’s to return the shortest word out of a string:

function findShort(s) {
  s = s.split(" ");
  let shortest = s[0];
  for (let i = 0; i < s.length; i++) {
    if (s[i].length < shortest.length) shortest = s[i].length;
  }
  return shortest;
}
console.log(findShort("bitcoin take over the world"));

In the end shortest variable will have the value of 4 and not the value of 3, I can’t understand why it doesn’t move to 3 because we will have the condition at some place in time i=3 if(3<4) shortest = 3;
the condition is true so why won’t we have it.

I know the solve to this it’s this:

function findShort(s) {
  s = s.split(" ");
  let shortest = s[0];
  for (let i = 0; i < s.length; i++) {
    if (s[i].length < shortest.length) shortest = s[i];
  }
  return shortest.length;
}
console.log(findShort("bitcoin take over the world"));

But I want to understand why it doesn’t work with the first method?

Click event to call a js file, then load contents into div

I would like to be able to click on the Orange text to be able to call the orange.js file, then load the .js file into the myTableResult div. I would like the name of the .js file to be inside the onclick event. Can somebody help me with that?

<a onclick="getScript('Orange.js');"/>Orange</a>

<div id="myTableResult">


</div> 
<script type="text/javascript" src="/myapp/htmlCode"></script>

how to display a dropped image file in browser on a canvas or as a HtmlImageElement ()

i actually wondering why the only way of doing this is taking the binary data from the file, base64-encode it and then feed this encoded String into an Tag / HtmlImageElement

Either as plain HTML

<img src="data:image/jpeg;base64,xxxxxxxxxxxxx...">

or via javascript

let reader = new FileReader();
reader.readAsDataURL( droppedFile ); // this converts the binary data from the file into base64
reader.onloadend = () => {
    const img = new Image();
    img.src = reader.result;
    img.onloadend = () => { 
        console.log(`image ${droppedFile.name} loaded.`);
    }  
}

A weird performance: Data is base64-encoded, which turns an 1MB Image into 1.33MB String (this really takes time), then placed inside the Image Element, just to be decoded again (which again takes time) to be displayed …

Why is that?

There is really no way to use TypedArray’s (UInt8Arrays) instead?

And where exactly does the browser check for the file type and retrieves width and height of lets say a dropped jpg file?

Unable to register default service worker. Service worker script threw an exception during script evaluation

I’m making an application using laravel as the backend and reactjs as the frontend using inertia, I’m trying to configure push notifications/browser notification in it using FCM.

Initially, they worked fine but when I got back to working on the project after some time, they didn’t work.

This is my firebase-messaging-sw.js

importScripts('https://www.gstatic.com/firebasejs/8.10.0/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging-compat.js');

const firebaseConfig = {
 apiKey: process.env.VITE_APP_FIREBASE_API_KEY,
 authDomain: process.env.VITE_APP_FIREBASE_AUTH_DOMAIN,
 projectId: process.env.VITE_APP_FIREBASE_PROJECT_ID,
 storageBucket: process.env.VITE_APP_FIREBASE_STORAGE_BUCKET,
 messagingSenderId: process.env.VITE_APP_FIREBASE_MESSAGING_SENDER_ID,
 appId: process.env.VITE_APP_FIREBASE_APP_ID,
 measurementId: process.env.VITE_APP_FIREBASE_MEASUREMENT_ID
};

firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();

messaging.onBackgroundMessage(payload => {
 console.log("Received background message ", payload);
 console.log(
      "[firebase-messaging-sw.js] Received background message ",
      payload
 );
 const notificationTitle = payload.notification.title;
 const notificationOptions = {
      body: payload.notification.body,
      icon: payload.notification.image
 };

 self.registration.showNotification(notificationTitle, notificationOptions);
});

this is App.jsx

async function registerServiceWorker() {
    if ("serviceWorker" in navigator) {
        navigator.serviceWorker
            .register("../../public/firebase-messaging-sw.js")
            .then(function(registration) {
                console.log("Service Worker Registered!");
            })
            .catch(function(error) {
                console.log("Service Worker Registration Failed: ", error);
            });
    }
}

// Call this function whenever you need to re-register the service worker
registerServiceWorker();

this is how I’m trying to get the device token:

  const getDevToken = async () => {
        Notification.requestPermission().then(async permission => {
            console.log(permission);
            if (permission === "granted") {
                const token = await getToken(messaging, {
                    vapidKey: import.meta.env.VITE_APP_VAPID_KEY
                });
                console.log(token);
                setData({
                    ...data,
                    deviceToken: token
                });
                setdevToken(token);
            }
        });
    };

I always get this error while trying to register the service worker

Uncaught (in promise) FirebaseError: Messaging: We are unable to register the default service worker. ServiceWorker script at http://127.0.0.1:8000/firebase-messaging-sw.js for scope http://127.0.0.1:8000/firebase-cloud-messaging-push-scope threw an exception during script evaluation. (messaging/failed-service-worker-registration).

I also get this:

Service Worker Registration Failed: DOMException: The operation is insecure.

I did trying checking if I had my service worker path wrong but that wasn’t the case.

Use Vue3 v-html without extra wrapping tag with script setup

How can I use vue’s v-html directive in a Vue 3 <script setup> environment without an extra wrapping tag?

I want to be able to do something like this:

<script setup>
const html = ref(`<pre></pre>`)
</script>

<template v-html="html"></template>

This code does work, but a 2-3 second delay can be observed when this approach is taken which is not ideal.

<script setup>
const html = ref(`<pre></pre>`)
</script>

<template>
  <template v-html="html"></template>
</template>

Is there a way we could create some kind of fragment component?

Blender physics animation in Three.js

So I made a working umbrella following this tutorial:
https://www.youtube.com/watch?v=fObSauc228g&t=130s (Part3/3)
my goal is to use this umbrella model in the web using Three.js, so I made some code which enabables me to import glb files and also play the animations of them.

here is the code:

import * as React from 'react';
import { Canvas, useFrame } from '@react-three/fiber';
import { Suspense, useState, useRef, useEffect } from 'react';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import { OrbitControls, useGLTF } from '@react-three/drei';
import * as THREE from 'three';

const Model = ({ playAnimation }) => {
const gltf = useGLTF(require("../svg/Part3.glb"));
const mixer = useRef();

// Increase the scale to make the model larger
gltf.scene.scale.set(200, 200, 200);

// Set up animation mixer
if (!mixer.current) {
    mixer.current = new THREE.AnimationMixer(gltf.scene);
    gltf.animations.forEach((animation) => {
        const action = mixer.current.clipAction(animation);
        action.play();
    });
    console.log(gltf.animations)
}

// Update the animation mixer on each frame
useFrame((state, delta) => mixer.current.update(delta));

// Play animation when playAnimation is true
useEffect(() => {
    if (playAnimation) {
        mixer.current.timeScale = 1;
    } else {
        mixer.current.timeScale = 0;
    }
}, [playAnimation]);

return <primitive object={gltf.scene} />;
};

const Umbrella = () => {
const [playAnimation, setPlayAnimation] = useState(false);

const handleButtonClick = () => {
    setPlayAnimation(!playAnimation);
};

return (
    <div>
        <Canvas camera={{ position: [0, 0, 1000], fov: 75, near: 1, far: 5000 }} style={{     

backgroundColor: "black", position: "relative", width: "100%", height: "90vh" }}>
            <directionalLight position={[2000, 2000, 2000]} intensity={1} color="white" />
            <pointLight position={[10, 10, 10]} intensity={0.6} />
            <Suspense fallback={null}>
                <Model playAnimation={playAnimation} />
            </Suspense>
            <OrbitControls />
        </Canvas>
        <button onClick={handleButtonClick}>{playAnimation ? 'Pause Animation' : 'Play Animation'}    

</button>
    </div>
);
};

export default Umbrella;

so I think the code should be fine, currently I am playing all the animations at the same time.
Anyways, when I exported my modle normaly and tested the animations in the web, all the in blender connected pieces didnt seem to be connected, since only the main piece moved. I found out that I need to bake the animations, so it works in the web. But one thing still causes problems, the cover of the umbrella uses the clothes physics of blender and is hooked to the support beams, so it follows them. (See pictures) This part doesnt work in Three.js, first I thought baking the physics could help but sadly it didnt.

Image of umbrella

To be clear, i dont mind if the animation is baked, I just need the animation to be playable and correct in the web using three.js.
I would realy like to provide you with my 3d modle, but I dont know how to do that in SO, please jsut reach out to me for the modle.

I look forward to your answers

Chart.js display data based on selection

I am looking for a solution to display some data based on what you hover on inside the chart. Here’s my jsfiddle and a demo of what I want.
gif image

I hope I’ve made everything clear, and thanks in advance!

const chart = document.getElementById('chart');

new Chart(chart, {
  type: 'doughnut',
  data: {
    labels: ['Bitcoin', 'Ethereum', 'Litecoin', 'Tether'],
    datasets: [{
      data: [50, 30, 10, 10],
      backgroundColor: [
        'orange',
        'purple',
        'darkblue',
        'green'
      ],
      borderWidth: 2,
    }]
  },
  options: {
    responsive: false,
    cutout: '72%',
    plugins: {
      legend: {
        display: false,
      },
    },
  }
});
.chart-wrap {
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart-balance {
  position: absolute;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<div class="chart-wrap">
  <canvas id="chart" class="kz-relative kz-index-10" width="224" height="224"></canvas>
  <div class="chart-balance">
    <p class="chart-asset-type">Ethereum</p>
    <h5 class="chart-asset-value">$1,000</h5>
  </div>
</div>

Click on text label [closed]

Im trying to click on a link on a web page by using the link label text “SCOTTISH PARLIAMENT 1 HORSE WYND OLD TOWN EDINBURGH” but don’t seem to be able to find the correct code to select it.

enter image description here

Ive tried numerous ways to select it without any luck –
“document.querySelector(‘.autocomplete-items label[textContent=”
and all combinations I could think of but could do with some help if possible please.
Thanks for any assistance.

How can I extract images from Word file(doc, docx) with Javascript

I am trying to extract contents from Word file with Node.js and I have already got text with mammoth.
But the image extraction doesn’t work well.
How can I complete it?
I am working on Node.js.

 mammoth.extractRawText({ path: req.file.path })
  .then(async (result) => {
        const images = result.messages.filter(message => message.type === "image");
            images.forEach((image, index) => {
                const { contentType, content } = image;
                const extension = contentType.split("/")[1];
                fs.writeFileSync(`image_${index}.${extension}`, content, 'binary');
            });
       }
    )

Deploying next app to Vercel failed “Error: Cannot find module “

I am trying to deploy Nextjs app to Vercel. I am getting this error: “Error: Cannot find module ‘/vercel/path0/.next/server/app/index/page_client-reference-manifest.js'”
i have tried everything but nothing changed.

i tried Delete node_modules and run yarn install.
Then do yarn build.
Then deploy
tried to use Vercel cli

nothing seems to work.

here is the error log


[15:32:30.569] info  - Need to disable some ESLint rules? Learn more here: https://nextjs.org/docs/basic-features/eslint#disabling-rules
[15:32:30.570]    Collecting page data ...
[15:32:31.474] Error: Cannot find module '/vercel/path0/.next/server/app/index/page_client-reference-manifest.js'
[15:32:31.475] Require stack:
[15:32:31.475] - /vercel/path0/node_modules/next/dist/server/load-components.js
[15:32:31.475] - /vercel/path0/node_modules/next/dist/build/utils.js
[15:32:31.476] - /vercel/path0/node_modules/next/dist/build/worker.js
[15:32:31.476] - /vercel/path0/node_modules/next/dist/compiled/jest-worker/processChild.js
[15:32:31.476]     at Module._resolveFilename (node:internal/modules/cjs/loader:1077:15)
[15:32:31.476]     at /vercel/path0/node_modules/next/dist/server/require-hook.js:55:36
[15:32:31.476]     at Module._load (node:internal/modules/cjs/loader:922:27)
[15:32:31.476]     at Module.require (node:internal/modules/cjs/loader:1143:19)
[15:32:31.476]     at mod.require (/vercel/path0/node_modules/next/dist/server/require-hook.js:65:28)
[15:32:31.476]     at require (node:internal/modules/cjs/helpers:119:18)
[15:32:31.476]     at loadClientReferenceManifest (/vercel/path0/node_modules/next/dist/server/load-components.js:43:72)
[15:32:31.477]     at loadComponentsImpl (/vercel/path0/node_modules/next/dist/server/load-components.js:65:29)
[15:32:31.477]     at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
[15:32:31.477]     at async /vercel/path0/node_modules/next/dist/build/utils.js:1077:32 {
[15:32:31.477]   code: 'MODULE_NOT_FOUND',
[15:32:31.477]   requireStack: [
[15:32:31.477]     '/vercel/path0/node_modules/next/dist/server/load-components.js',
[15:32:31.477]     '/vercel/path0/node_modules/next/dist/build/utils.js',
[15:32:31.478]     '/vercel/path0/node_modules/next/dist/build/worker.js',
[15:32:31.478]     '/vercel/path0/node_modules/next/dist/compiled/jest-worker/processChild.js'
[15:32:31.478]   ]
[15:32:31.478] }
[15:32:31.478] 
[15:32:31.478] > Build error occurred
[15:32:31.481] Error: Failed to collect page data for /index
[15:32:31.481]     at /vercel/path0/node_modules/next/dist/build/utils.js:1220:15
[15:32:31.481]     at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
[15:32:31.481]   type: 'Error'
[15:32:31.481] }
[15:32:31.566] error Command failed with exit code 1.
[15:32:31.567] info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
[15:32:31.588] Error: Command "yarn run build" exited with 1
[15:32:32.308] 

I have tried

Delete node_modules and run yarn install.
Then do yarn build.
Then deploy

also tried to use Vercel cli