Steps to alter the color of a JSONLoader-generated object with a simple click

Recently, I've been delving into Three.js and managed to create an object using the JSONLoader. The material of the object is currently grey in color.

My goal now is to allow users to change the color of the object by clicking on a button that I have added to the HTML.

<input type="button" value="Change Color" onClick="group.material.color.setHex('0xffffff')">

Upon checking DevTools, I encountered the following error message:

Cannot read property 'color' of undefined

I verified that the object does not contain the property 'color', so I understand why it did not work as expected.

Although I had a feeling it wouldn't work, I still hoped for the best. This is the snippet where the object is created:

group = new THREE.Object3D();

    //load mesh 
    var loader = new THREE.JSONLoader();
    loader.load('models/s_class.js',  function( geometry ) {
        mesh = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial( {color: 0x2f3a4c}) );
        mesh.scale.set( 10, 10, 10 );
        mesh.rotation.x = -Math.PI / 2;
        mesh.position.y = 0;
        group.add( mesh );
        scene.add( group );
    } );

Is there any way at all to simply change the color by clicking a button? Should I consider using a different Loader when building my object?

You can find my code on jsfiddle here.

Thank you in advance!!!

Answer №1

Instead of changing the color of the entire "group", focus on changing the color of each individual child element. One way to do this is by utilizing the traverse function.


group.traverse(function(child) {
    if (child instanceof THREE.Mesh){
        child.material.color.setHex('0xffffff');
    }
});

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

Create a function in JavaScript that can generate a random number a specified number of times based on user input

I have been struggling to develop a JavaScript program that can generate a random number multiple times based on user input. Despite numerous attempts, I haven't been able to get it to work. Below is the code snippet I've been working with: f ...

"Prisma vs. Supabase: A Comparison of Image Uploading

I am encountering an issue with adding image URLs to the Prisma database. I have successfully uploaded multiple images from an input file to Supabase storage, but when I try to add their URLs to the database, I receive an error regarding property compatibi ...

The command "bin" is not identified as an internal or external command in this npm script

I'm new to using node/npm and encountering an issue when attempting to start an npm script. Every time I try to execute a simple script like the one below, I get the error message "bin is not recognized as an internal or external command." I have suc ...

"Discover the best way to sort through an array of complex objects with varying levels of nesting using a specified search

I have come across similar answers, but none of them go beyond two levels deep. Therefore, I believe this is not a duplicate problem. My task is to filter an array of objects where each object may contain nested objects of unknown depth. In my data structu ...

Checking to see if the prop 'isChecked' has been modified

I'm currently facing a challenge with testing whether a class's prop value changes after clicking the switcher. Below is the component class I am working with: import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core&a ...

Storing Data with expressjs/session in NodeJS

My development project involves 3 files: app.js, index.js (routes), and Users.js (controller). Upon successful user login (verification between POST data and the database), I aim to store information in a session using expressjs/session. Below is how I c ...

Dynamic element not firing jQuery event

My question is...https://i.sstatic.net/me2uQ.png // Using ajax to dynamically create a table $(".n").click(function(){ var id= $(this).closest('tr').find('td.ide2').html(); //for displaying the table $.ajax({ ...

Combining Entities Using Immutable JavaScript

Currently utilizing React, Redux, and Immutable. I have a question about merging a plain JavaScript object into an Immutable Map object. Importing Immutable.js: import { List as iList, Map as iMap } from "immutable"; The content of action.paylo ...

Retrieving the result of a callback function within a nested function

I'm struggling with a function that needs to return a value. The value is located inside a callback function within the downloadOrders function. The problem I'm encountering is that "go" (logged in the post request) appears before "close" (logged ...

Use Javascript to display specific div elements by clicking a button

I could really use some assistance, When I attempt to display the select div by clicking the button, the "id" that PHP generates returns a null response in the console. The requirement is to only show the div when clicking on the "Quick Quote" button. Pro ...

Retrieve the text value of a selected option in a v-select component

After reading some documentation about v-select and slots, I am a bit confused about whether it can be applied to my specific scenario on this codepen. All I really need is to capture the selected text (not the value) and utilize it somewhere in the code: ...

Retrieving a variable in a JavaScript function while a webpage is in the process of loading

Recently, I was working on writing Selenium test cases in C# and encountered an issue while trying to capture a value from a webpage. The problem arose when the retrieved value was rounded to 5 decimal points which was not what I wanted. Instead, I needed ...

Developing a specialized command-line application for currency conversion is my current project

Currently, I am working on developing a command-line application for currency exchange. I have created an interface to define the structure of an object array that will store the keys and values of currency names along with their current values in the inte ...

Angular form displayed on the screen

I'm having trouble finding a solution to this issue, as the form data is not being output. var app = angular.module('myApp', []); app.controller('mainController', ['$scope', function($scope) { $scope.update = funct ...

Determine the number of rows in the Tabulator's table

Can anyone tell me how to retrieve the number of rows in a table created using Tabulator on a website? Is there a method like table.size or table.length that I can use for this purpose? The table has been initialized with the following code: table = new T ...

Looking for Efficiency in Basic JavaScript Arithmetic Operations

I'm having trouble figuring out how to display a total price after a selection is made. My goal is to take the selected value, multiply it by 100, and then use the updateTotal function to show the total. // Gather Data & Prices for Updating Dynamic P ...

Is there a way for me to retrieve SCSS color variables within the javascript of a Vue template?

I have a unique challenge in my application involving a component called Notification. To bring notifications to other components, I utilize the mixin method toast('message to display', 'color-variable'). My goal is to set the backgroun ...

What location is optimal for storing ng-templates within an Angular/Django single-page application?

My project involves using Django and AngularJS to create a single-page application. I have numerous ng-templates structured like this: <script type="text/ng-template" id="item.html"> // content </script> Currently, all these templates are l ...

Tips for swapping out a new line character in JavaScript

Hello! I'm currently facing a challenge with some code. I have a function designed to replace specific HTML character values, such as tabs or new lines. However, it's not functioning as expected. var replaceHTMLCharacters = function(text){ tex ...

How can I use jQuery to switch the positions of two <div> elements in HTML based on the selection of a dropdown value?

I need to switch the display positions of two <div> containers based on a dropdown value change. Can this be accomplished using jQuery? Here are the two div containers whose display positions need to be interchanged: <div id="first"><p> ...