Having trouble updating textures when clicking a button in Aframe

I'm attempting to load a gltf model and change the texture on button click using the register component. The model loads and displays as expected, but I'm having trouble reflecting any changes when the button is clicked for the texture change.

Here's my approach:

<div class=" radisi">
<input type='button' class='radmi rad1' value='next' /></div>

  <a-entity id="newmod" example gltf-model="src: url(model/straw.glb);"
              position="0 1.8 -1" scale="1,1,1"></a-entity>



    AFRAME.registerComponent('example', {

    init: function() {
    var el = this.el;
    el.addEventListener('model-loaded', function (e) {
    e.detail.model.traverse(function(child) {

        if (child instanceof THREE.Mesh){
             if (child.material.name == "Craem")  {
             material.map =   new THREE.TextureLoader().load( "assets/img/choco.png" );
                       }
                    }
                });
             })
          }
      },3000)

Upon registering the component, I'm trying to implement the texture change upon click:

$(".radisi").click(function(){

var el = this.el;
        el.addEventListener('model-loaded', function (e) {
        e.detail.model.traverse(function(child) {

            if (child instanceof THREE.Mesh){
                 if (child.material.name == "Craem")  {
                 material.map =   new THREE.TextureLoader().load( "assets/img/tri.png" );
                           }
                        }
                    });
                 })
});

An error message stating 'addEventListener of undefined' is displayed. Please advise on where I might be going wrong. Thank you.

Answer №1

You set up a component to listen for the model loading completion and change the material accordingly.

However, you also have a click listener that is listening for the model to load again, even though it most likely has already done so by that point. Additionally, using this.el within a jQuery-powered click listener may not work as expected since this.el is provided by the A-Frame component.

To resolve this issue, consider moving the click listener into the component itself and remove the model-loaded listener from the click event handling logic.

Answer №2

Revisiting the mesh once more has proven effective in resolving my issue.

$(".radisi").click(function(){

let obj  = el.getObject3D('mesh');

        obj.traverse(function(child) {

            if (child instanceof THREE.Mesh)
                    {
                        if (child.material.name == "Craem")  {
                             child.material.map=new THREE.TextureLoader().load( "assets/img/strawberry.png" );;

                                }
                    }
            });
});

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

What is the reason for the original list being affected when the cloning list is created using a

I am trying to convert an object inside an array into a string using the code below. However, I can't seem to understand why it's affecting the original array. I thought that 'slice' was supposed to clone the array? var cloned = $scope ...

Changing the color of specific sprites in three.js

I'm currently exploring three.js and encountering some difficulties when attempting to adjust the color of individual sprites in an array. My reference point is the example provided on this link from threejs.org. The specific task I am working on in ...

Set the timezone of a Javascript Date to be zero

Is there a way to create a Javascript date without any specific timezone? When I try to do so in Javascript, it automatically sets it to GMT Pacific standard time. let newDate = new Date(new Date().getFullYear(), 0, 2, 0, 0, 0, 0) }, newDate: Sat Feb 01 2 ...

Using Javascript to perform redirects within a Rails application

Currently working on a Facebook application using Rails. There are certain pages that require users to be logged in, otherwise they will be directed to a "login" page. I am unable to use redirect_to for this purpose as the redirection must be done through ...

Do you think there is a more optimal approach to writing if (argList[foo] === "bar" || argList === "bar")?

I have an if statement : if (argList["foo"] === "bar" || argList === "bar"){ // some code } I am curious if there is a concise or more elegant way to express this condition. The reason behind writing this statement is that I have two functions: st ...

Mastering the complexities of Javascript, AJAX, and PHP intertwined

Hello everyone, I'm currently working on a website in Codeigniter and I have a form that I submit using PHP, which works perfectly. However, I also have a small dropdown menu on the side of my page that allows users to jump between pages by clicking o ...

Is it possible to utilize md-select from Angular Materials to execute a function?

Encountering a peculiar issue with the md-select element - I may be using it incorrectly. The goal is to redirect to a new page or sign out based on the selected option, but instead, I'm faced with this error: Error: Failed to execute 'removeChi ...

Turn off the feature that prohibits the use of variables before they are

I'm struggling to disable this setting in my tsconfig file. The TS documentation doesn't seem to have any information about how to do it. no-use-before-declare I'm facing an issue where my test stub data objects are interfering with each ot ...

"""Exploring the use of query strings with jQuery for Ajax pagination

Here's the issue I'm facing (apologies for any mistakes in my English): I've been using a library called "Jquery_pagination" and the pagination functions perfectly without any issues. However, there is one problem. When a user clicks on a s ...

Is the order of execution of extraReducers before or after the reducers?

I was curious about the createSlice function in redux-toolkit and how it handles the order of execution for extraReducers compared to reducers. Can we determine if the extraReducers are executed before or after the reducers, or is the order indeterminate? ...

Unable to dynamically populate Bootstrap select with real-time search and multiple options using jQuery

How can I dynamically populate a select statement with options retrieved from PHP code? <select name='friends[]' id='friends' class='selectpicker show-tick form-control' data-live- search='true' multiple& ...

Enhancing Material-UI component [TreeView] with drag and drop functionality using react-dnd

I have encountered an issue with my TreeView implementation. Whenever I try to drag and drop a TreeItem, all of its child TreeItems move along with it. Is there a way to enable drag'n'drop functionality for just one TreeItem without affecting its ...

Maintaining Scene Integrity in THREE.JS: Tips for Handling Window Resizing

My layout includes a div with a scene that looks great initially; however, as soon as I start moving or resizing the window, the scene overflows the boundaries of the div and goes haywire, almost filling the entire window. Are there any techniques or solu ...

What is the process for incorporating a collection in Mongoose?

Trying to clear the Users collection before and after tests: before(function(done) { mongoose.connection.collections['users'].drop(function(err) { mongoose.connection.collections['users'].insert(user, done); }); }); after(func ...

Utilizing npm for managing several modules with distinct main entry points

In the process of developing a package that supports both CommonJS and ES Modules, I encountered an issue related to importing files from within the package. My current setup involves writing code as an ES module (ESM) and using Babel to compile it to Comm ...

What is the best way to run a JavaScript function once another function has finished executing?

I am looking to ensure that a JavaScript function runs only after another one has finished executing. Here is the code I currently have: $(window).load(function(){ $('#dvLoading').fadeOut(2000); }); window.addLoadEvent = function() { $('#p ...

Where can I locate information on using the .get method?

Recently, I encountered a code snippet on this site that helped me resolve an issue. The individual who provided the code utilized a .GET method that was unfamiliar to me. Here's a sample snippet: If you'd like to see the complete code, you can ...

Showcase the Uploaded Image Section within the Dropzone Display

https://i.sstatic.net/xzJWT.png Hello! I am currently working on implementing Dropzone.js to create a gallery. I've encountered a small issue where the default behavior of Dropzone displays a blank container area with a clickable effect to upload pho ...

Selenium's WebDriver getAttribute function can return an object of type "object",

In my selenium script, I aim to extract text from table columns following the cell with the specified value. Although the script functions, I encounter an issue where getText() returns [Object Object] in my node.js console. I have attempted various method ...

Unlimited Lunch Options and Navigational Links

Looking for help with displaying the ul for MAINTENANCE and referencing specified classes from a CSS style sheet that are working elsewhere. However, the sub menu for MAINTENANCE is not showing up. Any suggestions? /* * Superfish v1.4.8 - jQuery menu w ...