Why do my floating leaves appear at the same time and barely move?

I’m trying to create a floating leaf animation using CSS and a parallax effect with JavaScript. My goal is to have multiple leaves float in slightly different paths and timings across the screen.

But right now:

  • All the leaves appear at the same time, even though I added animation-delay.
  • The float animation moves them in a very small range.
  • I also added a mouse-based parallax effect and wonder if that’s interfering with the animation?

Here’s a simplified version of my code:

HTML:

<div class="floating-leaf" id="leaf1"><img src="images/leaf.png" /></div>
<div class="floating-leaf" id="leaf2"><img src="images/leaf.png" /></div>
<div class="floating-leaf" id="leaf3"><img src="images/leaf.png" /></div>

CSS

.floating-leaf {
  position: absolute;
  width: 24px;
  height: 24px;
  z-index: 1;
  animation: float 12s linear infinite;
  opacity: 0.7;
}

@keyframes float {
  0% {
    transform: translate(0, 0) rotate(0deg);
    opacity: 0;
  }
  10%, 90% { opacity: 0.7; }
  100% {
    transform: translate(100px, -100px) rotate(360deg);
    opacity: 0;
  }
}

#leaf1 { top: 80px; left: 10%; animation-delay: 0s; }
#leaf2 { top: 50px; left: 80%; animation-delay: 1s; }
#leaf3 { top: 30px; left: 45%; animation-delay: 2s; }

JavaScript (for parallax):

function initLeafParallax() {
  window.addEventListener('mousemove', function(e) {
    const leaves = document.querySelectorAll('.floating-leaf');
    leaves.forEach((leaf, index) => {
      const speed = (index + 1) * 0.03;
      const x = (window.innerWidth - e.pageX * speed) / 100;
      const y = (window.innerHeight - e.pageY * speed) / 100;
      leaf.style.transform = `translate(${x}px, ${y}px)`; // could this be overriding CSS animation?
    });
  });
}

How can I make the leaves float more realistically and not all show up at the same time?
Any help is appreciated!

Bootstrap modal working proper but not with overlay component

The current interaction behavior is that after I click submit the form, it should have delayed time with spinner and success message but they’re still not showing only modal close in setTimeout() inside showSuccess()

I have modal overlay after modal-footer and inside modal-content

<div id="modalOverlay" class="position-absolute top-0 start-0 w-100 h-100 d-flex flex-column justify-content-center align-items-center" style="z-index: 1000;">
    <div id="loadingSpinner" class="spinner-border text-primary d-none" role="status">
        <span class="visually-hidden">Loading...</span>
    </div>

    <div id="successMessage" class="alert alert-success mt-3 d-none" role="alert">
        Added Successully!
    </div>
</div>

function hideAddModal() {
    document.getElementById("modalOverlay").style.pointerEvents = "none";
    $("#addModal").modal("hide");
    $(".modal-backdrop").remove();
}
function showSpinner() {
    $("#loadingSpinner").removeClass("d-none");
    $("#successMessage").addClass("d-none");
    document.getElementById("modalOverlay").style.pointerEvents = "auto";
}
function showSuccess() {
    $("#loadingSpinner").addClass("d-none");
    $("#successMessage").removeClass("d-none");
    document.getElementById("modalOverlay").style.pointerEvents = "auto";

    setTimeout(function () {
        hideAddModal();
        $("#successMessage").addClass("d-none");
    }, 1000)
}

Below here is code snippet of submit function after button is triggered

bool isInserted = await InsertStored(value);
if (isInserted)
{
    BindGridView(); 
    Debug.WriteLine("Registering script to hide modal");
    ScriptManager.RegisterStartupScript(this, GetType(), Guid.NewGuid().ToString(),
    @"
    showSpinner();
    setTimeout(function() {
        showSuccess();
    }, 500);
    ",
    true);
}
else
{
    // Another ScriptManager to show alert error message
}

How do optimise Array.sort or what is the best way to sort large size JSON

i am using default array.sort method inside my application here is my sample code

  const jsonArray = Array.from({ length: 100000 }, (_, i) => ({
  id: i,
  principle: Math.random() * 1000,
  interest: Math.random() * 1000,
  maturity: Math.random() * 1000,
  maturity_date: new Date(Date.now() + Math.random() * 100000000).toISOString(),
  maturity_amount: Math.random() * 1000,
  maturity_amount_date: new Date(Date.now() + Math.random() * 100000000).toISOString(),
  maturity_amount_value: Math.random() * 1000,
  maturity_amount_date_value: Math.random() * 1000,
  maturity_amount_date_value_date: new Date(Date.now() + Math.random() * 100000000).toISOString(),
  maturity_amount_date_value_name: `Name ${Math.random() * 100000}`,
  maturity_amount_date_value_name_date: new Date(Date.now() + Math.random() * 100000000).toISOString(),
  maturity_amount_date_value_name_date_value: Math.random() * 1000,
  name: `Name ${Math.random() * 100000}`,
  value: Math.random() * 1000,
}));
//console.log(jsonArray);

console.time('Sort time');
const sortedArray = jsonArray.sort((a, b) => a.name.localeCompare(b.name)); // Sort by 'name' in ascending order
console.timeEnd('Sort time');

Which is taking 371 ms Sort time: 371.35400390625 ms what is the best way to sort this in such a way that time to bring sort time around 180ms or so.

Prisma won’t connect to the API I Created

Now that is the error when I try to save the course name the error handling message always pop up
so I checked connection of Prisma with MySQL database and it was fine.
I did npx prisma generate and npx prisma push db and it run fine.
So I was trying so understand the problem since every thing is well connected and the api is written right what is the problem here is the code and the error

this is the on Submit

const onSubmit = async (values: z.infer<typeof formSchema>) => {
    try{
        const reponse = await axios.post("/api/courses", values)
        router.push(`/teacher/courses/${reponse.data.id}`);
        toast.success("Course created successfully")
            }catch{
                toast.error("Something went wrong")
            }
    };

While this is the route.ts at the apicourses folder

import { db } from "@/lib/db";
import { auth } from "@clerk/nextjs/server";
import { NextResponse } from "next/server";

export async function POST(
    req: Request,
) {
    try {
        const { userId } = await auth();
        const { title } = await req.json();

        if (!userId) {
            return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
        }

        const course = await db.course.create({
            data: {
                title,
                userId,
            },
        });

        return NextResponse.json(course);

    } catch (error) {
        console.log("[COURSES]", error);
        return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
    }
}
npm run dev

> [email protected] dev
> next dev

   ▲ Next.js 15.3.1
   - Local:        http://localhost:3000
   - Network:      http://192.168.1.15:3000
   - Environments: .env

 ✓ Starting...
 ✓ Ready in 6.7s
 ○ Compiling /middleware ...
 ✓ Compiled /middleware in 4.5s (224 modules)
<w> [webpack.cache.PackFileCacheStrategy] Serializing big strings (117kiB) impacts deserialization performance (consider using Buffer instead and decode when needed)
 ○ Compiling /teacher/create ...
 ✓ Compiled /teacher/create in 19.9s (1659 modules)
 GET /teacher/create 200 in 22577ms
 ○ Compiling /favicon.ico ...
 ✓ Compiled /favicon.ico in 2.2s (1017 modules)
 GET /favicon.ico 200 in 2729ms
 ○ Compiling /api/courses ...
 ✓ Compiled /api/courses in 2.1s (1667 modules)
Initializing Prisma Client...
 ⨯ Error: @prisma/client did not initialize yet. Please run "prisma generate" and try to import it again.
    at eval (libdb.ts:8:35)
    at <unknown> (rsc)/./lib/db.ts (D:WorkMy ProjectsLMSrpm-lms0.2.nextserverappapicoursesroute.js:33:1)
    at __webpack_require__ (D:WorkMy ProjectsLMSrpm-lms0.2.nextserverwebpack-runtime.js:33:42)
    at eval (webpack-internal:///(rsc)/./app/api/courses/route.ts:5:65)
    at <unknown> (rsc)/./app/api/courses/route.ts (D:WorkMy ProjectsLMSrpm-lms0.2.nextserverappapicoursesroute.js:22:1)
    at __webpack_require__ (D:WorkMy ProjectsLMSrpm-lms0.2.nextserverwebpack-runtime.js:33:42)
    at __webpack_require__ (D:WorkMy ProjectsLMSrpm-lms0.2.nextserverwebpack-runtime.js:33:42)
    at __webpack_exec__ (D:WorkMy ProjectsLMSrpm-lms0.2.nextserverappapicoursesroute.js:184:39)
    at <unknown> (D:WorkMy ProjectsLMSrpm-lms0.2.nextserverappapicoursesroute.js:185:309)
    at __webpack_require__.X (D:WorkMy ProjectsLMSrpm-lms0.2.nextserverwebpack-runtime.js:168:21)
    at <unknown> (D:WorkMy ProjectsLMSrpm-lms0.2.nextserverappapicoursesroute.js:185:47)
    at Object.<anonymous> (D:WorkMy ProjectsLMSrpm-lms0.2.nextserverappapicoursesroute.js:188:3)
   6 |
   7 | console.log("Initializing Prisma Client...");
>  8 | export const db = global.prisma || new PrismaClient();
     |                                   ^
   9 |
  10 | if (process.env.NODE_ENV !== "production") {
  11 |     global.prisma = db; {
  page: '/api/courses'
}

How to debug extension service worker silently failing

When working on a extension service worker (MV3), many times a bug will cause the service worker to silently fail, making it remain inactive, and as far as I can tell without a way to attach Chrome DevTools to it, making it very difficult to determine what is the bug to begin with.
For example if I include something like:

import { dne } from './not-a-file';

anywhere in the service worker or imported submodules, it will not activate. And any communication will silently fail as well, for example calling from the popup window (and obviously calling sendResponse on the other end):

console.log("before message");
const response = await chrome.runtime.sendMessage("hello");
console.log("after message");
console.log(response);

will only log

before message

in the DevTools attached to the popup window. Is there a way to deal with these silent failures?

Calculating offset to center a card in a carousel

I’m working on this React x Motion carousel that brings a card to the center of the screen when it has been clicked, depending on its index. However, the cards only seem to be placed at the start of the carousel list.
Here is the code below.

import { motion } from "motion/react";
import { useState } from "react";

const carouselImages = [
  "../img-11.jpg",
  "../img-2.jpg",
  "../img-13.jpg",
  "../img-4.jpg",
  "../img-15.jpg",
  "../img-1.jpg",
  "../img-19.jpg",
  "../img-3.jpg",
  "../img-14.jpg",
  "../img-5.jpg",
];

export default function StaggerCarousel() {
  const [selectedIndex, setSelectedIndex] = useState(0);

  const handleOnClick = (e) => {
    const clickedItem = e.currentTarget;
    const clickedIndex = Array.from(clickedItem.parentNode.children).indexOf(
      clickedItem
    );
    setSelectedIndex(clickedIndex);
  };

  return (
    <div className="carousel-container w-screen h-screen flex items-center justify-center bg-gray-900">
      <motion.ul className="carousel-list flex items-center h-full overflow-hidden w-[90vw] md:w-150 gap-4">
        {carouselImages.map((img, index) => {
          return (
            <motion.li
              key={index}
              className="carousel-item w-48 h-48 rounded-lg shrink-0 cursor-pointer"
              animate={{
                translateX: `-${selectedIndex * 100}% `,
                y: selectedIndex === index ? -20 : 10,
                rotate: selectedIndex === index ? 0 : 5,
                opacity: selectedIndex === index ? 1 : 0.5,
                transition: {
                  duration: 0.05,
                  //   delay: index * 0.1,
                  type: "spring",
                  stiffness: 100,
                },
              }}
              style={{
                backgroundImage: `url(${img})`,
                backgroundSize: "cover",
                backgroundPosition: "center",
              }}
              onClick={handleOnClick}
            ></motion.li>
          );
        })}
      </motion.ul>
    </div>
  );
}

I can visualize that the calculation will be dependent on the windowWidth and itemWidth, and I’ve tried something like that, but it doesn’t give the exact result.


  const itemWidth = 208;

  const windowWidth = window.innerWidth / 2;

  const offsetX = windowWidth + itemWidth / 2 - selectedIndex * itemWidth;
  console.log(offsetX);

Unknown JSON.stringify issue [duplicate]

I’ve been writing a chatbot for a site, and am working on a command that gives a (non–existant, fake) currency on the bot to buy fun items, and I’m using localStorage and JSON objects for that.

But, I’ve encountered an issue when updating the balance of the user and creating a new balance value for the user, here are the details:

if (localStorage.balances == undefined) {
    localStorage.setItem('balances', '{"ffdbddfaae": "0"}') // initialize balance so JSON doesn't error out
}
let balances = JSON.parse(localStorage.balances) // convert string to JSON object for further changes

let addToBalance = function(value, id) {
    if (id.replace(/[0-9]/g, '') in balances) { // convert alphaumerical id string to only letters to not cause errors when using balances.(id) and check if id exists in balance object
        Object.defineProperty(balances, id.replace(/[0-9]/g, ''), {
            value: parseInt(balances[id]) + value // add value to balance 
        })
        localStorage.setItem("balances", JSON.stringify(balances))
    } else {
        Object.defineProperty(balances, id.replace(/[0-9]/g, ''), {
            value: value
        })
        localStorage.setItem("balances", JSON.stringify(balances))
    }
}
addToBalance(100, "ffdbddfaae")
addToBalance(69, "foobarid")

The code should work in theory, but it doesn’t.
Here is how I analyzed the code.

  1. Try isolated code in isolated environment
  2. Check localStorage.balances
  3. Note that it didn’t change at all
  4. Dissect the problem

So when dissecting the problem, I found out that when JSON.stringify()ing the new balances variable (not to be confused with localStorage.balances), instead of being '{"ffdbddfaae": 100, "foobarid": 69}', it was just '{"ffdbddfaae": 0}', aka the first value that localStorage.balance was set to, so, in practice, localStorage.balance was changing to its own value, creating no effect whatsoever.

Any reason why that happens?
Maybe I’m just too new to JSON.

page history combined with the history of an iframe on the page

I’m working in an application written in Perl, JavaScript, CSS, and C. I have a visual with an iframe that loads an application about the visual and a history.go(-1) breadcrumb. If I click into the application in the iframe and then click the breadcrumb, it backs through the iframe history before leaving the visual. The visual and iframe history seem combined. I would like to allow a client to explore the application in the iframe and leave the visual page without backing through the iframe history. I have tried some eventlisteners and have been looking at the iframe-history,js function set on Gethub. So far, I’ve not been able to do it. Any guidance would be appreciated. Thanks.

tsconfig/linter to prevent named import of CJS module from ESM

To import a CJS module from an ESM module, the “default import” has to be used, while named imports cause an error when ran.

// Errors as lodash is CJS module.
import { get } from 'lodash';

// OK.
import _ from 'lodash';
const get = _.get;

Is there a way to detect, in the code IDE, incorrect named imports of CJS module, via tsconfig, eslint, or otherwise?

Javascript dynamic javascript file loading then execution

here is the execution of my javascript:

ee_btn.addEventListener('click', () => {
        //Ajax GET request to get data form and rendering it
        RequestEEFormData(container, bounds).then(()=>{
            // Loading a javascript file. it get loaded.
            // I can call function from this file then.
            loadScript('/static/js/locationConverterWidget.js');
        });
        
    });
function loadScript(url) {
    const script = document.createElement('script');
    script.src = url;
    script.async=false;
    script.onload = function(){
        //trying to querySelector newly added content
        console.log(document.querySelector('#id_item);
    }
    document.head.appendChild(script);
  }

in case:


async function RequestEEFormData(container, bounds) {
    $.ajax({
        type: 'GET',
        url: 'someURL/',

        success: function (response) {
           container.innerHTML=response;
           someFunction(bounds)
        },
        error: function(response){
          console.log(response);
        },
        cache:false,
        contentType: "application/json",
        processData: false
     });
}

the console.log return an empty Nodelist.

if I do call the same consol.log from a button 1sec later. It work.

Clearly there is something with the async I dont understand.

Can anyone explain my what I’m doing wrong ?

the purpose is I want the newly downloaded javascript file to querySelector newly added content but It seems to be executed prior the html is completely rendered.

thank you

react-map-gl Popup displaying under deck.gl layers

I’m using a react-map-gl Popup component (maplibre implementation) inside a DeckGl component, and while I can get the Popup to open, it seems to be displaying under the deck.gl layers. To illustrate what’s happening vs the desired behavior, in the image below, the green border should be visible over the pink circle:

deckgl layer vs popup:

My component structure is as follows:

<DeckGL
  layers={layers}
  initialViewState={INITIAL_VIEW_STATE}
  controller={true}
>
  <Map reuseMaps mapStyle={MAP_STYLE}>
    {selectedLocation && (
      <Popup
        longitude={selectedLocation.geometry.coordinates[0]}
        latitude={selectedLocation.geometry.coordinates[1]}
        closeButton={true}
        onClose={() => setSelectedLocation(undefined)}
        offset={[0, -15]}
      >
        <h3>HELLO WORLD</h3>
      </Popup>
    )}
  </Map>
</DeckGL>  

And my layer config is:

const layers = [
  new GeoJsonLayer({
    id: "PinkDotsLayer",
    data: pinkDotsGeoData,
    getPointRadius: 25,
    getFillColor: [255, 0, 255],
    pickable: true,
    onClick: handleLocationClick,
  }),
  new GeoJsonLayer({
    id: "PurpleDotsLayer",
    data: purpleDotsGeoData,
    getPointRadius: 25,
    getFillColor: [128,0,128],
    pickable: true,
    onClick: handleLocationClick,
  }),
];

I’m aware of the integration modes documentation, but I’m not quite sure how to modify my code accordingly as the provided code sample does not work for me.

How should I go about getting the Popup to display at the top-most layer?

How do I use console.log in JavaScript? [closed]

I’m just starting to learn JavaScript and I keep seeing people use console.log().

Can someone explain:

What the JavaScript console is?

How do I use it to test or debug my code?
your text
Here’s what I’ve tried:

javascript
Copy
Edit
console.log(“Testing the console”);

Trying to add markers to Trimble Map in React with Javascript SDK but markers are shifting off the map and not at inputted lat long

Im trying to use trimble maps javascript sdk in a react app to display a map. I also want to add points to the map at specified lat longs. However, whenever I add a marker to the map the marker appears to shift off the map and not show at the lat/long. When you zoom in or out the marker does look like it moves.

I will also note that I have also been adding routes to the map with the lat longs and those work and show where they should. So this issue is just with the markers.

The version of trimble Im using is: “@trimblemaps/trimblemaps-js”: “^4.2.1”

If theres a better method for adding markers to the map I can switch to that. I just cant understand why the marker is being shifted. I copied this from examples on the trimble developer portal so Im not sure what Im doing wrong. I will say the examples on trimble are just javascript and I am doing this in react so Im not sure if that is making a difference or not.

import React, { useEffect } from 'react';
import './TrimbleTestPage.css';
import TrimbleMaps from "@trimblemaps/trimblemaps-js";

TrimbleMaps.setAPIKey("API KEY");

export default function TrimbleTestPage() {

useEffect(() => {
    const center = [-87, 38];
    const zoomLevel = 6;
    const map = new TrimbleMaps.Map({
        container: 'map', // container id
        center: center,
        zoom: zoomLevel,
        maxCanvasSize: [500,1000],
        region: TrimbleMaps.Common.Region.NA
    });

    map.on('load', () => {
        // Create a marker with a label on top of an icon
    const el = document.createElement('div');
    el.classList.add('cust-marker');
    el.title = 'Marker with a label and an icon';
    const htmlContent =
        '<div id="text">Green truck</div>' +
        '<div id="image" style="background: url(https://maps.alk.com/api/1.2/img/truck_green.png) no-repeat; height: 26px; width: 26px;"/>';
    el.innerHTML = htmlContent;
    const marker = new TrimbleMaps.Marker({
        draggable: false,
        anchor: 'top-left', // default: center, if width is too wide, you will see marker moves after zoom out.
        element: el
    }).setLngLat(center).addTo(map);
    });

    // Cleanup function to remove the map instance when the component unmounts
    return () => map.remove();        
}, []);

return (
        <div style={{width: "100%", height: "100%"}}>
            <div id="map" style={{height: "500px", width: "1000px;"}}></div>
        </div>
)
}

Here is what the map looks like with the marker when it renders:
Screenshot of page rendered

Tailwind 4.1 Transition for flex item not working

so I’m having a weird issue with Tailwind and it’s transitions. I have a parent div with a background color that changes depending on the activeState. This has a transition and it works just fine.

Within that div I have a “dot” that toggles between being on the left and the right, depending on it’s activeState. The transition on this does not work.

I’m not sure why the second div’s transition isn’t working. I’ve tried changing the code to be an absolute div with left-1 right-1 being what it toggles between but that also didn’t work.

   <div
            className={`flex items-center ${
              activeState ? "bg-red-400 " : "bg-gray-600 "
            } w-11 h-6 rounded-full transition-all px-[2px]`}
          >
            <div
              className={`bg-white w-5 h-5 rounded-full ${
                activeState ? "ml-auto" : "mr-auto"
              } transition-all`}
            ></div>
          </div>