Cannot use import statement outside a module (Vanilla JS)

I’m getting Cannot use import statement outside a module(Vanilla Javascript) while testing a simple demo app locally using nano server.

data.js

const data = {
    "type": "Feature",
    "properties": {
        "name": "Coors Field",
        "amenity": "Baseball Stadium",
        "popupContent": "This is where the Rockies play!"
    },
    "geometry": {
        "type": "Point",
        "coordinates": [-104.99404, 39.75621]
    }
}

export {data};

index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Supercluster Leaflet demo</title>

        <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha256-kLaT2GOSpHechhsozzB+flnD+zUyjE2LlfWPgU04xyI=" crossorigin="" />
        <script src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha256-WBkoXOwTeyKclOHuWtc+i2uENFpDZ9YPdf5Hf+D7ewM=" crossorigin=""></script>

        <link rel="stylesheet" href="cluster.css" />

        <style>
            html, body, #map {
                height: 100%;
                margin: 0;
            }
        </style>
    </head>
    <body>
        <div id="map"></div>
        <script type="module" src="data.js"></script>
        <script src="index.js"></script>
    </body>
</html>

index.js

import {data} from 'data.js';

/*global L */

// The rest not needed

JavaScript Embedding and Extraction in PDFs

I want to embed some JS code into a pdf that extracts the content of a line and auto runs on open.
I tested it out by just running app.alert and it worked on MSEdge.

What JS Modules/methods would I have to use to achieve this. Any answer helps

I have tried finding modules online and the ones I have found are all working from the outside, asking for file name. I am looking for JS code that I want to embed into my PDF that extracts the content of backend line 57 and runs app.alert(line 57)

Javascript callbacks fundamentals from C# point of view

Please help me understand two thing about callbacks. They are the last JS weirdness left for me that I can’t grasp having strong C# background.

First – why should we send function as parameters. I know that we can, but why. I will try the simplest example I can think of. So according to the JS developers it should be like this:

function simpleCallbackFn (){}

function simpleCallerFn (cb){ cb();}

simpleCallerFn (simpleCallbackFn);

Why not like this:

function simpleCallbackFn (){} // Same as before

function simpleCallerFn (){ simpleCallbackFn ();}  

We do not pass a callback, we simply call it from within the caller. It is within perfectly visible scope. Then we just make the initial call.

simpleCallerFn ();

Calling the “callback” function from within the caller function to me should be perfectly fine and achieve the same result.

Second – say I need to use callback with arguments

function simpleCallbackFn (anArgument){}

function simpleCallerFn (cb){ 
   cb(anArgument);
}

We know that this will not work
simpleCallerFn (simpleCallbackFn(anArgument));

According to the JS developers it should be like this:

simpleCallerFn (() => simpleCallbackFn(anArgument));

I am thinking why not:

function simpleCallbackFn (anArgument){}

function simpleCallerFn (anArgument, cb){ 
   cb(anArgument);
}

Then make the initial call like this:

simpleCallerFn (anArgument, simpleCallbackFn);

Please. That Javascript makes me fell like in freak’s circus.

Thank you.

Is there a way to make the balls generate at random positions within the canvas?

function setup()
{
 createCanvas(800, 600);

//other code has been omitted
}

function generateRandomBalls() {

    var numRows = 5; // we have 4 rows, 5 including the top row
    var radius = 8;
    var startX = Math.random();
    var startY = Math.random();

    for (var row = 0; row < numRows; row++) {
        for (var i = 0; i <= row; i++) {
            var xOffset = row * (sqrt(3) * radius);
            var yOffset = row * (radius * 3) / 2;
            var x = startX + xOffset;
            var y = startY - i * (radius * 3) + yOffset;

            var ball = Bodies.circle(x, y, 11, {
                restitution: 1,
                friction: 0.5,
                render: { fillStyle: 'red' }, // we set the color of the ball to red
                velocity: { x: 1, y: 2 },
                //collisionFilter: { group: 0x0002 }
            });
            Body.setAngle(ball, PI / 2); // we change the angle from -PI/2 to PI/2 to flip the triangle
            balls.push(ball);
        }
    }

    
    World.add(engine.world, balls);
}

The code should make the positions of the red balls are within the canvas at random but always remain with a grid-style (triangle style) shape, so that every time the game starts, it start at a random position of the canvas.

webpack 5 and mini-css-extract-plugin doesn’t load the css after saving the scss to css files

I have mini-css-extract-plugin that creates the css files from my scss files fine, but it when I load my pages (reactJs app), there are no styles loading. I suspect I am messing up the paths for output or import in some way, but I have tried many combinations unsuccessfully… The paths for import worked fine with the inline style-loader before.
webpack entry:

entry: {    
        index: './src/index.js',
    },
    output: {
        filename: '[name].js'
    },

webpack module:

module: {
        rules: [
        {
        test: /.(sass|less|css|scss)$/,
        sideEffects: true,
        use: [
          
           MiniCssExtractPlugin.loader,
          "css-loader",
          "sass-loader",
        ],
      },          
        {
          test: /.js?$/,
          exclude: /node_modules/,              
          loader: 'babel-loader',          
          options:{
            presets: ['@babel/preset-react']
          }
        }

    ],          
  },

Webpack plugins:

plugins: [
        new MiniCssExtractPlugin({
          filename: "css/[name].css",
          chunkFilename: "css/[id].css",
        })
    ]

mainListing.js (which is one of the React routes inside of index.js):

import './css/index.scss'

Cannot fetch data from the backend [ JWT Laravel React ]

I am using Reactjs, Laravel and JWT. I am trying to login and fetch data from the backend into dashboard after I log in but it gives me “Request failed with status code 500”. I have tried with get instead of post but doesnt work. If I removed “http.post” stuff in dashboard.js it doesnt give error but I need it as I need user’s details.

Laravel
api.php

Route::post('login', [AuthController::class,'login']);
Route::post('register', [AuthController::class,'register']);

Route::group(['middleware'=>'api'],function(){
    Route::post('logout', [AuthController::class,'logout']);
    Route::post('refresh', [AuthController::class,'refresh']);
    Route::post('me', [AuthController::class,'me']);
});

Reactjs :
Auth.js

export default function AuthUser(){

const navigate = useNavigate();

const getToken = () =>{
    const tokenString = sessionStorage.getItem('token');
    const userToken = JSON.parse(tokenString);
    return userToken;
}

const getUser = () =>{
    const userString = sessionStorage.getItem('user');
    const user_detail = JSON.parse(userString);
    return user_detail;
}



const [token,setToken] = useState(getToken());
const [user,setUser] = useState(getUser());

const saveToken = (user,token) =>{
    sessionStorage.setItem('token',JSON.stringify(token));
    sessionStorage.setItem('user',JSON.stringify(user));

    setToken(token);
    setUser(user);
    navigate('/dashboard');
}

const logout = () => {
    sessionStorage.clear();
    navigate('/login');
}

const http = axios.create({
    baseURL:"http://localhost:8000/api",
    headers:{
        "Content-type" : "application/json",
        "Authorization" : `Bearer ${token}`
    }
});
return {
    setToken:saveToken,
    token,
    user,
    getToken,
    http,
    logout
}
}

Dashboard.js

import { useEffect, useState } from 'react';
import AuthUser from './AuthUser';

export default function Dashboard() {

const {http} = AuthUser();
const [userdetail,setUserdetail] = useState('');

useEffect(()=>{
    fetchUserDetail();
},[]);

const fetchUserDetail = () =>{
    http.post('/me').then((res)=>{
        setUserdetail(res.data);
    });
}

function renderElement(){
    if(userdetail){
        return <div>
            <h4>Name</h4>
            <p>{userdetail.name}</p>
            <h4>Email</h4>
            <p>{userdetail.email}</p>
        </div>
    }else{
        return <p>Loading.....</p>
    }

}

return(
    <div>
        <h1 className='mb-4 mt-4'>Dashboard page</h1>
        { renderElement() }
    </div>
)
}

I am trying to follow https://github.com/AjayYadavAi/react-js-authentication-laravel tutorial but it works on his and not mine. I did the exact same thing.

A Links redirecting to directory error but files in directory exist

i made a navigation bar and somehow my a link elements inside of it are not redirecting me to the given files. This is made in replit.

Code:

index.html

<nav>
        <a href="#">Home</a>
        <a href="./frontend/features.html">Features</a>
        <a href="./frontend/pricing.html">Pricing</a>
        <a href="./frontend/contact.html">Contact</a>
        <a href="./frontend/">Login</a>
    </nav>

server.js

const express = require("express");


const app = express();

app.get('/', function(req,res) {
  res.sendFile("./index.html", { root: "./frontend" });
  console.log("ooga booga")
});


app.listen(8080)

Picture of directory: directory

ive tried multiple ways of getting the frontend folder:

./frontend/ /frontend/ frontend/

I expected myself being able to click on the a element buttons and the file being shown

i get an error that reads: Cannot GET /frontend/features.html

I have created a cursor using html, css and javascript which is built on this website now the problem is the cursor is moving but not scaling

I have created a cursor using html, css and javascript which is built on this website now the problem is the cursor is moving but not scaling like on this website scale down with cursor movement I want the cursor to move on this website along with scaling down. How can I make it?
This is the link to this website
https://redlight.dev/careers/

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="styles.css" />
    <title>Custom Cursor</title>
    <style>
      body {
        cursor: none; /* Hide the default cursor */
        margin: 0;
        overflow: hidden;
      }

      .custom-cursor {
        position: fixed;
        width: 20px;
        height: 20px;
        background-color: #ff0000; /* Choose your desired color */
        border-radius: 50%;
        pointer-events: none;
        transition: transform 0.2s ease-out;
        transform-origin: center;
      }
    </style>
  </head>
  <body>

    <div class="custom-cursor"></div>
    <!-- Your content goes here -->
    <script>
      document.addEventListener("DOMContentLoaded", function () {
        const cursor = document.querySelector(".custom-cursor");

        document.addEventListener("mousemove", function (e) {
          const x = e.clientX;
          const y = e.clientY;

          cursor.style.transform = `translate(${x}px, ${y}px)`;
        });
      });
    </script>
  </body>
</html>

html/javascript next and back buttons

i’m trying to code a div with next/back buttons that change the content shown in the div when they’re clicked. i could do this by just having it go to a different page entirely, but that would require me to make a lot of pages and i don’t want to do that. this likely has an extremely easy solution but unfortunately i am not very smart when it comes to javascript . i’ve tried looking online for tutorials but none of them are showing me what i’m trying to achieve.

i have very basic code for this here:

<!DOCTYPE html>
<html>
<body>

<div id="changediv">click the button</div>
<button onclick="myFunction()">the button</button>

<script>
function myFunction() {
  document.getElementById("changediv").innerHTML = "one";
  document.getElementById("changediv").innerHTML = "two";
}
</script>

</body>
</html> 

what’s supposed to happen is when the button is clicked it shows “one”, and then when the button is clicked while it’s showing “one” it goes to “two” and so on so forth. instead it just skips straight to two.

Replicate Reanimated V1 animation in Reanimated V2/V3

I’m working on transitioning (pun intended) my app from React Native Reanimated V1 to V3. I have a transition that I want to stay exactly the same, but I’m not sure how to write it in Reanimated 3. Here is the code for the old transition, which looks like this (ignore the slight up and down motion, the transition is triggered on page scroll).

enter image description here.

import {
  Transitioning,
  Transition,
  TransitioningView
} from 'react-native-reanimated';

const transition = (
  <Transition.Together>
    <Transition.Out type="scale" durationMs={100} />
    <Transition.Change interpolation="easeInOut" />
    <Transition.In type="scale" durationMs={100} delayMs={50} />
  </Transition.Together>
);

const Component = () => {
  const transitioningRef = useRef();

  return (
    <Transitioning.View ref={transitioningRef} transition={transition}>
      {endThresholdTriggered ? (
        <ChevronDown marginBottom={15} size={25} opacity={1} />
      ) : (
        <Minus marginBottom={15} size={25} opacity={0.45} />
      )}
    </Transitioning.View>
  );
};

This is what I have so far with Reanimated 3. It’s fading in and out just fine, but doesn’t have the “pop” that the old one does. Code for this is below

enter image description here

{startThresholdTriggered ? (
  <Animated.View
    key="startThresholdTriggeredIcon"
    entering={FadeIn}
    exiting={FadeOut}
  >
    <ChevronUp marginTop={15} size={25} opacity={1} />
  </Animated.View>
) : (
  <Animated.View
    key="startThresholdNotTriggeredIcon"
    entering={FadeIn}
    exiting={FadeOut}
  >
    <Minus marginTop={15} size={25} opacity={.45} />
  </Animated.View>
)}

Where do i place my url in webPDFLoader from langchain?

I’m trying to just load a pdf from a URL. I’m confused how to do so using the webPDFLoader. If anyone has a bit of time, please help explain how to implement this? I would appreciate any help pls.

I’m doing this in nextjs. Where in the webPDFloader section do I put the pdfUrl variable?

"use client";
import React, { useEffect } from "react";
import { WebPDFLoader } from "langchain/document_loaders/web/pdf";
import { guestPdfId } from "@/components/Hero";
import { Document } from "react-pdf";



const bucketId = process.env.NEXT_PUBLIC_APPWRITE_BUCKET_ID!;
const fileId = guestPdfId;
const projectId = process.env.NEXT_PUBLIC_APPWRITE_PROJECT_ID!;

const pdfUrl = `https://cloud.appwrite.io/v1/storage/buckets/${bucketId}/files/${fileId}/view?project=${projectId}&mode=admin`;

// webPDFLoader
const blob = new Blob(); // e.g. from a file input

const loader = new WebPDFLoader(blob, {
  // you may need to add `.then(m => m.default)` to the end of the import
  pdfjs: () => import("pdfjs-dist/legacy/build/pdf.js"),
});

docs = loader.load()

const docLen = docs.length()

const ProcessPdf = () => {

  return <div>
    <button onClick={doclen}>Show PDF</button>
</div>;
};

export default ProcessPdf;

chart.js v4.1.1 legend position not working

I’ve tried a few things to get the legend to appear to the right of the pie chart but nothing is working so far.

I’ve tried these in the options but the legend always appears on top, which I assume is the default.

legend: {
    position: 'right',
},

// or this
plugins: {
  legend: {
     display: true,
     position: 'right',
     align: 'center'
  }
}

I’ve been through a bunch of posts and went through the documentation on the chart.js website. What am I missing?

Here’s the code

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

$.ajax({
    type: "POST",
    url: "/Home/GglProjectPriority",
    data: '{}',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: onSuccess,
    error: onError
});

function onSuccess(data) {
    console.log(data);
    var _data = data;
    var _chartLabels = data[0];
    var _chartData = data[1];

    var options = {
        type: 'pie',
        title: 'Project Priority',
        data: {
            labels: _chartLabels,
            datasets: [{
                data: _chartData
            }]
        },
        legend: {position: 'right'},
        responsive: true,
        legend: {
            position: 'right',
        },
        // plugins: {
        //     legend: {
        //         display: true,
        //         position: 'right',
        //         align: 'center'
        //     }
        // }
    };
    new Chart(projectChart, options);
}

Thanks in advance for your help.

404 Error: HTML file of React project final build cannot find model variable

I am making a React project with Vite. In my html file, I have this:
stlLoader.load('/src/assets/model.stl')

This works perfectly fine in the dev environment. However, when I build the project (npm run build), I guess everything gets packed up and changed to weird letters and variables, so the script in my html file cannot find the “/src/assets/model.stl”. Instead, I get a 404 not found.

I am looking for a way to be able to load this model in my html file in my final build. Any help would be appreciated. 🙂

Sliderjs Change text of prev and next button with a data attribute text and in that must show the the previous and next slide data attribute text

Like the title, i need to change the next and prev text with the next and prev slide , not the current one that im seen.

on my current slide and in my next and previous button i like to see the text , text-slide , and text-slide

const swiper = new Swiper('.swiper', {
loop: true,
spaceBetween: 30,
pagination: {
el: ".swiper-pagination",
},
navigation: {
nextEl: '.next',
prevEl: '.prev',
},
on: {

  init: function() {
updateCaptionText(this);
  },
  activeIndexChange: function() {
updateCaptionText(this);
  }

}

});
let prev = document.querySelector('.prev');
let next = document.querySelector('.next');

function updateCaptionText(slider) {
    let prev_text = document.querySelector('.prev-text');
    let next_text = document.querySelector('.next-text');
    console.log(slider.slides[slider.realIndex - 1]);
    prev_text.innerHTML=slider.slides[slider.realIndex - 1].dataset.currentslide
    next_text.innerHTML=slider.slides[slider.realIndex + 1].dataset.currentslide
}