What could be the reason why Three.js animation doesn't seem to function properly within a <div> element but works perfectly fine within the <body> of an HTML document

Having trouble getting a Three.js animation to work inside a div? It works fine when placed directly on the body, right? The issue seems to be related to how it is appended.

The JavaScript code has a notable difference where the container is appended:

  • document.body.appendChild(container);
  • document.getElementById('for_three').appendChild(container);

If you switch back to

document.body.appendChild(container);
and remove
<div id="for_three"></div>
from the HTML file, the Three.js animation functions correctly within the body.

Please note that due to length restrictions, I couldn't include a live preview. However, you can find the identical code in this CodePen example.

HTML:

<!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>Three.js animation</title>
            <style>
                body { margin: 0; }
            </style>
            <link rel="stylesheet" type="text/css" href="style.css">
        </head>
        <body>
            <script src="three.js"></script>

            <div id="for_three"></div>
        </body>
</html>

CSS:

#for_three {
        position: absolute;
        width: 50%;
        height: 50%;
        margin-top: 10%;
        margin-left: 25%;
        background-color: bisque;
}

JS:

// three.js - https://github.com/mrdoob/three.js

var SEPARATION = 100,
    AMOUNTX = 100,
    AMOUNTY = 70;
 
var container;
var camera, scene, renderer;
 
var particles, particle, count = 0;
 
var mouseX = 85,
    mouseY = -342;
 
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
 
init();
animate();

// More JavaScript code...

function render() {

    // Rendering logic here...

}

Answer №1

The issue arises when your script is being executed prematurely before the

<div id="for_three"></div>
element is even created in the HTML document. As a result, the script cannot locate the div as it has not been generated yet. This is due to the fact that web browsers process HTML content sequentially from top to bottom. To resolve this problem, simply rearrange the order so that your <script> tag is placed at the end of the document:

<body>
    <div id="for_three"></div>
    <script src="three.js"></script>
</body>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for formatting strings to be compatible with JSON.parse

I'm encountering an issue with my node.js application where I am attempting to parse a string using JSON.parse. Here is the code snippet: try{ skills = JSON.parse(user.skills); }catch(e){ console.log(e); } The string stored in user.skill ...

How to handle a Node.js promise that times out if execution is not finished within a specified timeframe

return await new Promise(function (resolve, reject) { //some work goes here resolve(true) }); Using Delayed Timeout return await new Promise(function (resolve, reject) { //some work goes here setTimeout(function() { resolve(true); }, 5000); } ...

We apologize, but the module you are looking for cannot be found: Unable to locate 'fs'

Trying to create a new MDX blog website using Next.js 13 with the latest app router, but encountering an error message saying "Module not found: Can't resolve 'fs'". It was working fine in Next.js 12 and pages directory, but not in the lates ...

What is the best method for searching through all keys of an object?

Multiple documents contain a key called userId, where this key is always an object: { "id": { "$oid": "22fc6b11a0ff111d598b114f" }, "userId": { "KEY1" : ["..."], "KEY2" : ["..."], ...

Is the Ajax response value consistently 1?

I am facing an issue where a JavaScript in an HTML page is sending two variables to a PHP script, which then echoes one of the variables at the end. However, the response value always remains 1. Despite trying methods like alerting, console.log, and puttin ...

Transferring the value of a variable from Block to Global Scope in FIRESTORE

I'm currently working on an App in Firebase, utilizing FireStore as my primary Database. Below is a snippet of code where I define a variable order and set it to a value of 1. Afterwards, I update the value to 4 and use console.log to verify. Everyt ...

Using Selenium WebDriver in JavaScript to Extract Text from an Array

During my experimentation with Selenium webdriver in javacript, I encountered a challenge when trying to extract text from an array of WebElements (specifically cells within a table). The usual command getText() did not work as expected when attempting to ...

NodeJs ERROR: Module not found

When trying to launch an instance running ubuntu with express, I encountered a module not found error that does not occur on my Windows machine. Error Message: node:internal/modules/cjs/loader:1085 throw err; ^ Error: Cannot find module './src/c ...

Can JavaScript be used to change the style and make a hidden input field vanish from view?

Currently, I am designing a table containing dates along with numerous hidden fields. print "<td"; { $dm=date('Y-m-d',strtotime("+".$i." days", strtotime($m))); print " class=\"overflow\" id=\"$a::$dm\" onclick=\" ...

Origin Access-Control-Allow Not Recognized

Currently, I am developing a node.js app and have encountered a strange issue: This particular Angularjs snippet... // delete hosts $scope.delete = function(row) { var rowData = { hostname: row.hostname, ipaddr: row.ipAddress, ...

How can you make a button in Vue only visible after all API calls have successfully retrieved the data?

Is there a way to make the report button visible only after all the data has been loaded from the latest click of the budget button? Currently, when the budget button is clicked, it retrieves budgets and displays them in a Vue grid using Kendo Grid. To spe ...

Deciphering unidentified Json data

Having some trouble with an error in my note taker app built using expressjs. Everything was working fine until I tried to save a new note and it's throwing this error: SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse () Here&apos ...

Expanding functions consist of numerous components

How can I modify this script to work on multiple elements? For example, if a user clicks on a specific link (see demo) labeled "I'd like to expand the article linked here", only that particular link should expand an element, not all like it currently ...

What is the best way to display a Bootstrap pop-up and then automatically hide it after a few seconds

Does anyone know how to display a Bootstrap popup when the page loads and automatically hide it after 3 seconds? I found an example online but I'm unsure how to adapt the code for my specific needs. <button type="button" class="btn btn-primary" da ...

Refresh the block's content seamlessly without the need for a page reload

Within the index.html page There exists a block called content that contains various content blocks. An additional navigation menu with numerous links is present. It is important that when you click on a menu link, the content within the content block re ...

What is the reason behind fullstack-angular generator utilizing Lo-Dash's merge rather than document.set?

This is the original code snippet used for updating: exports.update = function(req, res) { if(req.body._id) { delete req.body._id; } Thing.findById(req.params.id, function (err, thing) { if (err) { return handleError(res, err); } if(!thing) { ...

Interacting with an XML file contained within a PHP variable using jQuery

I'm pretty new to programming, so please be patient with me =] Currently, I am working on passing a string from the user to an API using PHP. The API then responds with an XML file, which I store under $response. So far, everything is running smoothl ...

Update in Angular version 1.5.9 regarding $location.hashPrefix causing changes

Previously, the default $location.hashPrefix was an empty string until version 1.5.8 of AngularJS, but it was changed to "!" in version 1.5.9. This modification has caused issues in my codebase where there are instances like <a ng-ref="/Customer#/{{cu ...

The AJAX callback is unable to access the method of the jQuery plugin

I have a scenario where I am fetching data from an AJAX response and attempting to update a jQuery plugin with that value within the success callback: $.ajax({ url: '/some/url', type: 'GET', dataType: 'json', succ ...

Manipulating SVG image color using JavaScript

Is there a way to change the colors of an svg image using Javascript? Perhaps by loading it as an object and accessing the color/image data? I would greatly appreciate any responses or tips on this matter! ...