javascript importing modules with threejs and three-globe using only the browser and CDNs

I am trying to use threejs and three-globe together, using only the CDN distributions from unpkg, but I am getting tripped up by modules. I am hoping to avoid using a build tool but perhaps that’s not doable.

I started with the very basic example right from the top of the three.js README. I have an index.html:

<!DOCTYPE html>
<html lang="en">
        <head>
                <meta charset="utf-8">
                <title>Threejs basic app</title>
                <style>
                        body { margin: 0; }
                </style>

<script type="importmap">
        {
                "imports": {
                        "three": "https://unpkg.com/three/build/three.module.js"
                }
        }
</script>
        </head>
        <body>
                <script type="module" src="./main.js"></script>

        </body>
</html>

and a main.js, copied from the jsfiddle:

import * as THREE from 'three';

const width = window.innerWidth, height = window.innerHeight;

// init

const camera = new THREE.PerspectiveCamera( 70, width / height, 0.01, 10 );
camera.position.z = 1;

const scene = new THREE.Scene();

const geometry = new THREE.BoxGeometry( 0.2, 0.2, 0.2 );
const material = new THREE.MeshNormalMaterial();

const mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );

const renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( width, height );
renderer.setAnimationLoop( animation );
document.body.appendChild( renderer.domElement );

// animation

function animation( time ) {

        mesh.rotation.x = time / 2000;
        mesh.rotation.y = time / 1000;

        renderer.render( scene, camera );

}

And all works fine.

Where I get tripped up is when I want to include three-globe. If I try to import it like so, as the first line of the three-globe README suggests:

import * as THREE from 'three';
import ThreeGlobe from 'https://unpkg.com/[email protected]/dist/three-globe.js';


const width = window.innerWidth, height = window.innerHeight;

// rest of the code is the same

This fails, with the javascript console telling me

Uncaught SyntaxError: The requested module 'https://unpkg.com/[email protected]/dist/three-globe.js' does not provide an export named 'default' (at main.js:2:8)

No problem, it’s not a module, let me try what I think is the module version:

import * as THREE from 'three';
import ThreeGlobe from 'https://unpkg.com/[email protected]/dist/three-globe.mjs';


const width = window.innerWidth, height = window.innerHeight;

// init
//rest of the code is the same

This fails, because I apparently to help it find dependencies:

Uncaught TypeError: Failed to resolve module specifier "kapsule". Relative references must start with either "/", "./", or "../".

So I tried with a namespace import:

import * as THREE from 'three';
import * as ThreeGlobe from 'https://unpkg.com/[email protected]/dist/three-globe.js';

const width = window.innerWidth, height = window.innerHeight;

// init
// the rest of the code is the same

But now it blows up trying to mess with three.js:

Uncaught TypeError: Cannot read properties of undefined (reading 'BufferGeometry')
    at three-geojson-geometry.mjs:235:19
    at three-globe.js:5:98
    at three-globe.js:6:3

Looking at this code in three-geojson-geometry, it’s rooting around and looking for window.THREE – is it not there yet?

I can make this work by ditching the import of threejs and three-globe and just using them as script tags and not modules: the new index.html:

<!DOCTYPE html>
<html lang="en">
        <head>
                <meta charset="utf-8">
                <title>Threejs basic app</title>
                <style>
                        body { margin: 0; }
                </style>

<script type="importmap">
        {
                "imports": {
                        "three": "https://unpkg.com/three/build/three.module.js"
                }
        }
</script>
  <script src="//unpkg.com/three"></script>
  <script src="//unpkg.com/three-globe"></script>
        </head>
        <body>
<script type="module" src="main.js"></script>
        </body>
</html>

and the an updated main.js

//import * as THREE from 'three';
//import * as ThreeGlobe from 'https://unpkg.com/[email protected]/dist/three-globe.js';

const width = window.innerWidth, height = window.innerHeight;

// init

const camera = new THREE.PerspectiveCamera( 70, width / height, 0.01, 10 );
camera.position.z = 1;

const scene = new THREE.Scene();
//rest of the code is the same

And that works. But now when I want to import something in main.js, I get warnings about pulling in multiple versions of three.js

an updated index.html:

<!DOCTYPE html>
<html lang="en">
        <head>
                <meta charset="utf-8">
                <title>Threejs basic app</title>
                <style>
                        body { margin: 0; }
                </style>

<script type="importmap">
        {
                "imports": {
      "three": "https://unpkg.com/[email protected]/build/three.module.js",
"three/addons/": "https://unpkg.com/[email protected]/examples/jsm/"
                }
        }
</script>
  <script src="//unpkg.com/three"></script>
  <script src="//unpkg.com/three-globe"></script>
        </head>
        <body>
<script type="module" src="main.js"></script>
        </body>
</html>

and an updated main.js

//import * as THREE from 'three';
//import * as ThreeGlobe from 'https://unpkg.com/[email protected]/dist/three-globe.js';

import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';

const width = window.innerWidth, height = window.innerHeight;

// init
// all of the rest of the code is the same

That works, but now it’s upset that there are multiple three.js instances:

WARNING: Multiple instances of Three.js being imported.
(anonymous) @ three.module.js:53034

Following along in the network tab, https://unpkg.com/three 302s to https://unpkg.com/[email protected] which 302s to https://unpkg.com/[email protected]/build/three.js. The glTF module also looks like it’s creating a load for https://unpkg.com/[email protected]/build/three.module.js which presumably is the 2nd copy of Three.js

So trying to head that off at the beginning, and loading it index.html:

<!DOCTYPE html>
<html lang="en">
        <head>
                <meta charset="utf-8">
                <title>Threejs basic app</title>
                <style>
                        body { margin: 0; }
                </style>

<script type="importmap">
        {
                "imports": {
      "three": "https://unpkg.com/[email protected]/build/three.module.js",
"three/addons/": "https://unpkg.com/[email protected]/examples/jsm/"
                }
        }
</script>
  <script type="module" src="https://unpkg.com/[email protected]/build/three.module.js"></script>
  <script src="//unpkg.com/three-globe"></script>
        </head>
        <body>
<script type="module" src="main.js"></script>
        </body>
</html>

I’m now stuck with two errors in the console:

Uncaught TypeError: Cannot read properties of undefined (reading 'BufferGeometry')
    at three-globe:2:58460
    at three-globe:2:227
    at three-globe:2:238
(anonymous) @ three-globe:2
(anonymous) @ three-globe:2
(anonymous) @ three-globe:2

Uncaught ReferenceError: THREE is not defined
    at main.js:10:16

So I guess I’m just kinda stuck. Is there really no way to just do an import ThreeGlobe from main.js? I think my trouble is that ThreeGlobe is looking to hook onto the global THREE object, but I don’t understand when that is actually created if I only import it in main.js. This is kind of a longshot, but is there some await magic I have to do with these loads to make sure that any sideeffects of the module loads have happened?

window.getComputedStyle return CSS max-height with unresolved calc() function

I have a problem with function from topic in my Angular project. I have this code:

console.log(window.getComputedStyle(this.frontLayer.nativeElement).maxHeight);

and in component template:

 <div #frontLayer        
      [style.maxHeight]="maxHeight"
      [style.height]="curHeight"
      [style.minHeight]="minHeight">

The maxHeight property is set in ngOnInit.

Unfortunately, result that I receive is unresolved and looks like this:

calc(100% - 56px)

Does someone know how to fix this?

Thanks for your time.

How can I prevent Selenium opening multiple instances of Firefox when running a test?

I am writing some automated tests using Selenium Webdriver on Node.js. So far they are working fine, but I have one problem: Whenever I run a test (just 1 test), 4 instances of Firefox open. The test will run and complete in one of the FF windows, but the others will remain open.

Is this something to do with the asynchronous approach?

Would anyone know how I could limit how many instances of FF open when I run a test?

My code is as such:

const { Then, Given, When, After } = require('@cucumber/cucumber');
const assert = require('assert');
const { Builder, By, until, Key } = require('selenium-webdriver');
const firefox = require('selenium-webdriver/firefox');

let options = new firefox.Options();

const driver = new Builder()
    .forBrowser('firefox')
    .setFirefoxOptions(options)
    .build();


Given('I am on a page that needs to be tested', async function () {
    driver.wait(until.elementLocated(By.tagName('h1')));
    await driver.get('https://www.awebsite.com');
});

When('I do the thing', async function() {
   //.....tests, etc

The output I get in console running the test is:

Selenium Manager binary found at /me/automated-testing/node_modules/selenium-webdriver/bin/macos/selenium-manager
Driver path: /me/.cache/selenium/geckodriver/mac-arm64/0.34.0/geckodriver
Browser path: /Applications/Firefox.app/Contents/MacOS/firefox
Driver path: /me/.cache/selenium/geckodriver/mac-arm64/0.34.0/geckodriver
Browser path: /Applications/Firefox.app/Contents/MacOS/firefox
Driver path: /me/.cache/selenium/geckodriver/mac-arm64/0.34.0/geckodriver
Browser path: /Applications/Firefox.app/Contents/MacOS/firefox
Driver path: /me/.cache/selenium/geckodriver/mac-arm64/0.34.0/geckodriver
Browser path: /Applications/Firefox.app/Contents/MacOS/firefox
.....

1 scenario (1 passed)
3 steps (3 passed)
0m04.525s (executing steps: 0m04.517s)

As you can see, FireFox is opened 4 times. I am unsure how to restrict this so only 1 instance opens. Would anyone know how to do this?

.js files not running

I am trying to make a basic app in electron, but the .js files corresponding to my html pages are not running.

I thought that it was because of poor code on my part but have tried following several different guides to the tee to see if the issue still arises there but in all of them the .js for the corresponding html never runs. Their breakpoints are also unbound. My best guess is that there is something wrong with node_modules (there is quite a lot of stuff in there) but I don’t know what it could possibly be. There was also an app with preload.js where if I moved the code from index to preload it worked, but im not too sure if that’s related or not.

As for an example of the kind of guide im following,
https://khanrabby.blogspot.com/2020/08/electron-how-to-loadupdate-current.html
would be one. tried another one from geeksforgeeks as well. main.js can load up index.html but buttons just don’t work. No error messages.

I feel like I’m messing up something quite basic, but I’m not sure what it could possibly be.

main.js runs completely fine, though.

Importing bootstrap into nextjs – document is not defined

I am trying to import bootstrap 5.3.2 (not react-bootstrap) into a NextJS 14.1.0 project that uses new the new App Router. I would like to use individual BS components programmatically (not via data-attrs).

I got it to work but (I do get the tooltips) but I cannot get rid of this error 500 with each hard refresh. The console shows this exact message:

 ⨯ node_modules/bootstrap/dist/js/bootstrap.esm.js (803:18) @ document
 ⨯ ReferenceError: document is not defined
    at __webpack_require__ (/Users/rsilva/Desktop/bs/.next/server/webpack-runtime.js:33:42)
    at eval (./app/TooltipComponent.js:9:67)
    at (ssr)/./app/TooltipComponent.js (/Users/rsilva/Desktop/bs/.next/server/app/page.js:162:1)
    at __webpack_require__ (/Users/rsilva/Desktop/bs/.next/server/webpack-runtime.js:33:42)

Here’s my relevant code:

layout.js

import "bootstrap/dist/css/bootstrap.css";
import BootstrapProvider from "./providers/bootstrap";

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body className="container my-5">
        <BootstrapProvider/>
        {children}
      </body>
    </html>
  );
}

my BS provider (bootstrap.js):

"use client";

import { useEffect } from 'react';

function BootstrapProvider() {
  useEffect(() => {

    async function loadBootstrap() {
      const bootstrap = await import('bootstrap/dist/js/bootstrap.bundle.min.js');
      window.bootstrap = bootstrap;
    }

    loadBootstrap();
    
  }, []);

  return null;
}

export default BootstrapProvider;

page.js

import { TooltipComponent } from "./TooltipComponent";

export default function Home() {
  return (
    <main>
      
     <TooltipComponent title="Test">
        test tooltip
      </TooltipComponent>
      
    </main>
  );
}

and finally the actual component that uses Tooltip programatically:

"use client";

import { useEffect, useRef } from "react";
import { Tooltip } from "bootstrap";

export function TooltipComponent({
  children,
  title = "Missing tooltip 'title' property",
  placement = "top",
  trigger = "hover",
}) {
  const tooltipRef = useRef();

  useEffect(() => {
    if (title) {
      const tooltip = new Tooltip(tooltipRef.current, {
        title: title,
        placement: placement,
        trigger: trigger,
        container: "body",
      });
      return () => {
        tooltip.dispose();
      };
    }
  }, [title]);

  return <span ref={tooltipRef}>{children}</span>;
}

Any ideas? Thank you!

canvas and js basic game with colors

Hi, does anybody know why black lines from the begining disappear after some time? it is really hard to post on this site it took me 30mins fr

elemTop = c.offsetTop + c.clientTop;
c.addEventListener("click", function(event){
var x = event.pageX - elemLeft,
y = event.pageY - elemTop;
let i = Math.floor(x/50)
let j = Math.floor(y/50)
colorit(i,j)})`

`function drawthis(i,j){
ctx.moveTo(i * 50,  j * 50 );
ctx.lineTo(i * 50 + 50,  j * 50);
ctx.lineTo(i * 50 + 50,  j * 50 + 50 );
ctx.lineTo(i * 50,  j * 50 + 50);
ctx.moveTo(i * 50,  j * 50 );
ctx.stroke();}`

`function givrand (){
return Math.floor(Math.random() * 256);}

function colorit(i,j){
let r = givrand();
let g = givrand();
let b = givrand();
> `ctx.fillStyle = "rgba(" + r + "," + g +"," + b + ", 0.3)";
ctx.fillRect(i * 50, j * 50, 50, 50);}
`
setInterval(function(){
let i = Math.floor(Math.random()*(600/50));
let j = Math.floor(Math.random()*(600/50));
colorit(i,j)
},10);


for (let i =0 ; i < 600/50; i++){
for(let j = 0; j < 600/50; j++){
drawthis(i,j)
}}``
`
please help! thanx if you can tell me how to fix this i would be grateful !!!! 
it is for my first project still new to all this js and html css 
new to stack owerflow tooo

thanks yaaaal !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Why does nothing shows when I set dynamic query in my useQuery?

I’m struggling to get the data once I set it to dynamic query.

I get the data if I console.log during the axios call, but when I tried to call it on using resultQuery in my component. I get an empty result.

ApiAction.js

export const getUserResult = async (from, end, year, college , type) => {
  try {
    const response = await axios.get(`http://localhost:5000/api/result/query?from=${from}&end=${end}&year=${year}&college=${college}&type=${type}`)
    //const response = await axios.get(`http://localhost:5000/api/result/query?from=8&end=10&year=23&college=COLLEGE OF ENGINEERING AND INFORMATION SCIENCES&type=Students`)
    console.log(response.data)
    return response.data;
  } catch (error) {
    // Handle errors here if needed
    console.log(error)
  }
};

This is my useQuery call.

export const resultQuery = () => {
    const { isPending, error, data, isFetching, refetch } = useQuery({
        queryKey: ['result'], // Update this to match your API call key
        queryFn: getUserResult,
        enabled: false
    })

    return { isPending, data, error, isFetching, refetch }
}

Component.js

  const {isPending, data: UserResults, error, isFetching, refetch} = resultQuery()

  console.log(UserResults)
const handleClick =  () => {
    // Do something with resultData if needed
    //console.log(data.from, data.end, data.endYear, data.college, data.type)
    getUserResult(data.from, data.end, data.endYear, data.college, data.type)
    refetch()
  };

In this image, I get the data through console.log in the ApiAction.js, but when I tried to console.log on the component, I get an empty `array

enter image description here

I am having an issue with adding data to firbase database using html and javascript

I’m currently working on a project for my Future Business Leaders of America (FBLA) endeavor, focusing on developing an application form using HTML. As part of this project, I’ve created an HTML form for prospective general managers to apply for positions within our organization. The form encompasses essential fields such as full name, email, date of birth, address, and highest level of education attained.

To enhance the functionality of the application form, I sought to integrate it with a Firebase database using JavaScript. Below is the JavaScript code snippet I’ve implemented to facilitate this integration:

import { initializeApp } from "https://www.gstatic.com/firebasejs/10.7.2/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/10.7.2/firebase-analytics.js";
import { getDatabase, ref, set, get, child } from "https://www.gstatic.com/firebasejs/10.7.2/firebase-database.js";

const firebaseConfig = {
  apiKey: "AIzaSyDX5_CEU9gR9zdl2BBy2qUkF4kSyb0JYjE",
  authDomain: "fblawebdev2024.firebaseapp.com",
  databaseURL: "https://fblawebdev2024-default-rtdb.firebaseio.com",
  projectId: "fblawebdev2024",
  storageBucket: "fblawebdev2024.appspot.com",
  messagingSenderId: "1032509491070",
  appId: "1:1032509491070:web:fc458bc9c30ecfe810d52f",
  measurementId: "G-YV373ERG9K"
};


const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);


const db = getDatabase(app);

document.getElementById("General Manager Application Form").addEventListener('click', function (e) {
  e.preventDefault();
  set(ref(db, 'user/' + document.getElementById("fullName").value), {
    name: document.getElementVal('fullName').value,
    email: document.getElementVal('email').value,
    dob: document.getElementVal('dob').value,
    address: document.getElementVal('address').value

  });
  alert("Application Sent !");
})

here is the apply.html code

<
    <h1>General Manager Application Form</h1>
    <form id="General Manager Application Form" action="thankyou.html">

      <label for="fullName">Full Name:</label>
      <input type="text" id="fullName" name="fullName" required />

      <label for="email">Email:</label>
      <input type="email" id="email" name="email" required />

      <label for="dob">Date of Birth:</label>
      <input type="date" id="dob" name="dob" required />

      <label for="address">Address</label>
      <input
        type="text"
        id="address"
        name="address"
        required
        placeholder="Street Address"
      />

      <div class="address-fields">
        <input type="text" id="city" name="city" required placeholder="City" />
        <input
          type="text"
          id="state"
          name="state"
          required
          placeholder="State"
        />
        <input
          type="text"
          id="zip"
          name="zip"
          required
          placeholder="ZIP Code"
        />
      </div>
      
      <label for="education">Highest Level of Education:</label>
      <select id="education" name="education" required>
        <option value="">Select</option>
        <option value="High School">High School</option>
        <option value="Associate's Degree">Associate's Degree</option>
        <option value="Bachelor's Degree">Bachelor's Degree</option>
        <option value="Master's Degree">Master's Degree</option>
        <option value="Doctorate">Doctorate</option>
      </select>
    
    
      <script>
      
        document.querySelectorAll("textarea").forEach(function(textarea) {
            textarea.style.resize = 'none';
        });
    </script>

      <a href="thankyou.html" class="application1"
        ><button type="submit">Submit Application</button>
        <script src="mail.js" ></script></a
      >
      
    </form>
    <script src="main.js"></script>

Despite meticulously crafting the integration between the HTML form and Firebase database using JavaScript, I’ve encountered an issue where the data isn’t reflecting in the database upon submission. I’ve cross-checked the Firebase database configuration, ensured proper field mappings, and scrutinized the JavaScript event listener for any potential discrepancies. However, the database remains empty, failing to capture submitted application data.

Could you kindly review the provided JavaScript code and HTML form structure to identify any potential errors or misconfigurations that might be hindering the data submission process to the Firebase database? Your insights and guidance in resolving this issue would be immensely appreciated.

In my database, it shows nothing. Is there any error with my code?
enter image description here

How to display an alert box after a condition is met and a button is clicked

I am trying to figure out how to display an alert box saying “Please input a value” when a button is clicked and there is no text in the input box. Here is what I have tried so far:

const checkButton = document.getElementById("check-btn");
const textInput = document.getElementById("text-input");
const result = document.getElementById("result");

if (textInput.value = "" && checkButton.click()){
  window.alert("Please input a value")
}

This is not working though when i test it on freeCodeCamp’s test. What am I doing wrong?

const checkButton = document.getElementById("check-btn");
const textInput = document.getElementById("text-input");
const result = document.getElementById("result");

if (textInput.value = "" && checkButton.click()){
  window.alert("Please input a value")
}

Multiple actions for true (or false) in JS ternary shorthand syntax?

I have been picking up JavaScript recently, and was wondering what the proper syntax would be for setting multiple variables for each outcome in a shorthand ternary.

Here is an example of what I currently have, a shorthand ternary that changes 1 variable if a condition is met, and changes 1 other variable if it is not.

var numberA = 5;
let rltvToTen = '';
let otherVar = '';

numberA >= 10 ? rltvToTen = 'EqualOrGreater' : rltvToTen = 'Less';

console.log(`Relative to ten: ${rltvToTen}`);

What I’m wondering is how I could make this so that if numberA >= 10, it would still set rltvToTen to the string ‘EqualOrGreater’ but would, in that same step, set otherVar to the string ‘Lorem Ipsum.’

For example, for condition?ifTrue:ifFalse, I want to set multiple actions to occur for ifTrue

(Note: I’m aware that other tactics could be applied, but I’m genuinely curious as to whether there is a proper syntax that allows multiple actions set to occur given a condition back-to-back in the shorthand form.)

(Another note: I’m towards the end of the day and running on my last braincell, so I don’t doubt I may have phrased this in an unnecessarily confusing way, and I’m sorry for that.)

I tried just putting the actions back to back.
I tried , and ; to separate multiple actions.
I tried using a space to separate multiple actions.
I tried reading the relevant documentation.

The answer to this is likely right in front of me, but I probably just can’t see it cuz I’m a skiddie newgen lmao.

How to integrate a website written in React.js into Sulu CMS?

I have a website written in React.js and I need to throw it into Sulu CMS. I have researched how to do this and found ways to do it using API. It seems to me there are much simpler options…

I found a video describing that Sulu CMS has the ability to develop pages in React.js. I tried moving the site files to the webspaces folder, but it didn’t work 🙁

I can’t understand clearly that Date object in javascript [closed]

Date object examples I can’t understand that it work in that situationenter image description here.I have deadline for sale I wrote the codes but I can’t understand that How does it work

 const deadline = '2024-01-31';

  function getTimeRemaining(endtime){

    let timer = Date.parse(endtime) - Date.parse(new Date()),
        days = Math.floor(timer/(1000 * 60 * 60 * 24)),
        hours = Math.floor((timer/(1000 * 60 * 60)) % 24),
        minutes = Math.floor((timer/(1000 * 60)) % 60),
        seconds = Math.floor((timer)/(1000) % 60)

  }

Can you explain me that problem clearly?

Trying to access index inside an object

I’ve this piece of code:

var state = {}
function init(id) {
    state[id] = {
        house: {
            'test': [
                'hi',
                'hey'
            ]
        },
        car: {
            output: state[id].house['test'][0]
        }
    }
}
init(1);

But I’m getting Uncaught TypeError: Cannot read properties of undefined (reading 'house').

I already tried:

output: this.state[id].house['test'][0]
output: this.house['test'][0]
output: house['test'][0]

And none of them worked. How can I solve this? Thank you

here is the first part of code for canvas little game with polja

here is the first part and the next will be the second part:

they said i have to add more details they are like you have to tallk to old dude they just dont know when to stop fr

let canvas = document.getElementById("canvas")
let ctx = canvas.getContext("2d")

for(let i=0; i<10; i++){
for(let j=0; j<10; j++){
ctx.rect(i*50, j*50, 50, 50)
ctx.stroke()
}
}
window.addEventListener('keydown',this.check,false);
var a = 0
var b = 0
function crtajsliku(a,b){
var img = new Image();
img.onload = function(){
ctx.drawImage(img,a,b)
}

img.src="pikacu.png";
}
crtajsliku(a,b) 
let nx = 0
let ny = 0
var listanx = []
var listany = []
var brojac = 0
function check(e) {
var code = e.keyCode;
if (code == 38)
{
for(var i = 0; i<listanx.length; i++)
{
if(b-50 === listany[i] && a === listanx[i])
{
    brojac +=1
}
}
if (brojac === 0 && b-50 >= 0)
{   
ctx.clearRect(a,b,50,50)
ctx.rect(a,b,50,50)
ctx.stroke()
b -=50
crtajsliku(a,b)
console.log(a,b)
}else{brojac = 0}
}        

so here is the code for this game this is the first part i promise there will be the second one