The removeEventListener method seems to be malfunctioning when used within an if statement in my three.js code

I am relatively new to JavaScript, although I have a background in mathematics which includes concepts like coordinate systems and trigonometry. I've been learning JavaScript through Codecademy for the past couple of weeks, and recently attempted to create shapes in three.js by following tutorials on YouTube. Despite watching multiple tutorials on the same topic, I encountered an issue.

My project involves 5 objects that slightly rotate when you hover over them and revert back to their original position when the mouse moves away. Additionally, clicking on any object triggers a camera tween that moves closer to the selected object. Clicking on the same object again should return the camera to its original position.

I've set up event listeners for 'mousemove' and 'onclick', but my problem arises when I want to disable the hover effect after an object has been clicked and the camera has moved. I tried various approaches based on online resources and documentation, but nothing seems to work as intended. Perhaps there's something I'm overlooking, such as the inability to remove event listeners within if statements.

In my attempt to resolve this issue, I added code inside the click event block to disable the hover effect, but it didn't yield the desired result. Is there a way to disable the rotation tween specifically when the object is clicked?

Below are snippets of my code, including the object creation, camera animations, event listeners, and functions handling click and mouse movement interactions. Any assistance or guidance would be greatly appreciated as I strive to overcome this challenge and avoid disappointing my father, who has high expectations for this project.

Answer №1

Your current method of adding event listeners follows this pattern:

window.addEventListener("mousemove", (event) => {
    onMouseMove(event);
});

To remove them, you would do the following:

window.removeEventListener("mousemove", (event) => {
    onMouseMove(event);
});

It's important to note that by assigning two different anonymous functions to both method calls, it becomes impossible to remove the correct event listener. It's better to use this approach instead:

window.addEventListener("mousemove", onMouseMove);

And later on:

window.removeEventListener("mousemove", onMouseMove);

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

Fixing Cross-Browser Issues with the OnScroll Function

window.onscroll = function() { if( window.XMLHttpRequest ) { var bodyId=document.getElementById('bodymain'); if (bodyId.scrollTop > 187) { //make some div's position fixed } else { //mak ...

Tips for running a React custom hook selectively or within a specific function

I have created a unique custom hook to handle user redirection to the edit page. While on the index page, users can duplicate and delete items. The issue arises when deleting an item triggers the custom hook to redirect back to the edit page. I am looking ...

Unable to modify an attribute due to TypeScript error: Type 'string' cannot be assigned to type 'never'

I am trying to modify an attribute of an object in TypeScript and React, but I keep encountering the following error message: Type 'string' is not assignable to type 'never'. This happens even though I have a check in place to verify th ...

Verify whether a group of div elements overlaps a fixed div while scrolling

I have a layout with a list of posts and a logo positioned at the bottom of the page. The issue I am facing is that sometimes the title of the posts and the logo overlap, and I want to set the logo's opacity to 0.25 only when the text from .cat-date i ...

Promise and Determination failing to produce results

const { GraphQLServer } = require('graphql-yoga'); const mongoose = require('mongoose'); mongoose.connect("mongodb://localhost/test1"); const Todo = mongoose.model('Todo',{ text: String, complete: Boolean }); const ...

Disregard periods in URLs when configuring nginx servers

While developing with Vite in development mode via Docker on my Windows 10 machine, I encountered an issue where the local custom domain would not load due to a required script failing to load. The specific script causing the problem is /node_modules/.vit ...

The ValidationPipe in NestJS seems to be facing issues specifically with @Query() parameters

I've been attempting to convert certain query parameters from string to integer using the built-in NestJS ValidationPipe, but unfortunately, it doesn't appear to be functioning correctly. Below is my controller : import { ..., ValidationPipe } f ...

New feature alert! Introducing the Mentio JS menu now available at the bottom of the webpage

I am currently working on creating a Twitter-style @mention feature using Angular JS and a library called MentioJS. One issue I encountered is that after dynamically adding content to the page, a mysterious menu appears at the bottom of the page. This pro ...

Customizing Material UI tooltip styles with inline CSS formatting

Currently in the process of creating a React component that utilizes the Material UI Tooltip feature. In my component, I have the need to manually reposition the Mui Tooltip by targeting the root popper element (MuiTooltip-popper). However, the Mui Toolti ...

Guide to automatically updating a table with AJAX requests

My task involves utilizing AJAX to request a random string consisting of 10 numbers from an asp page. The numbers must be delimited by "||" and displayed in a table format. The table is designed to showcase only the top 10 results, with each new row addin ...

I am looking to retrieve a specific input value from a JSON array using JavaScript

I have created an array called 'PROPERTIES' which accepts values like username, password, sid, etc. I am looking to retrieve these entered values using JavaScript. 'PROPERTIES': {'gatewayurl': {'Name': ...

Generating Level of Detail information automatically

My scene is complex, filled with numerous small curved objects that have high polygon counts, leading to poor FPS. I've heard that using Level of Detail (LOD) optimization can greatly improve performance. I'm currently working with three.js, whi ...

Tips for converting ActiveRecord hierarchy into a JavaScript array

Currently, I am in the process of incorporating a treeview feature into my institution model within my rails application. To accomplish this, I have integrated the ancestry gem into my model successfully and included the treeview component into my view wit ...

What is the method for displaying map tooltips by default rather than on mouseover?

Currently, I have a script set up to display a map with two markers. Whenever I hover over one of the markers, a popup tooltip appears with location information. My question is, how can I make the information appear by default without needing to hover ov ...

If function is called after x seconds

Here is a JavaScript code snippet that triggers different functions based on the number of clicks. For instance, clicking once triggers function1, while clicking twice triggers function2. Now, how can I modify this code so that if I am in the stop_autosli ...

Having difficulty validating the field accurately with Angular.js

In order to validate the input field in accordance with the user's needs using AngularJS, I have shared my code below: <div ng-class="{ 'myError': billdata.longitude.$touched && billdata.longitude.$invalid }"> <input type ...

Module Ionic not found

When I attempt to run the command "ionic info", an error is displayed: [ERROR] Error loading @ionic/react package.json: Error: Cannot find module '@ionic/react/package' Below is the output of my ionic info: C:\Users\MyPC>ionic i ...

Can a Node.js dependent library be integrated into Cordova?

After setting up an android project using Cordova, I came across a javascript library that relies on node.js to function. Since Cordova operates with node.js, can the library be invoked within the Cordova environment? ...

Exploring end-to-end testing with NestJS and Guards

I'm trying to test an endpoint called /users using nestjs, but I encountered some errors. I'm unsure how to fix the issues and make the test pass with a guard. First Issue Nest is unable to resolve dependencies of the UserModel (?). Please en ...

The bond between Node.js and Express

I'm intrigued by the relationship between Node.js and Express. Here is my Node.js server creation code: const https = require('https'); const fs = require('fs'); const options = { key: fs.readFileSync('./https1/key.pem&ap ...