Disable event listener when the controls are unlocked using the pointerlock controls in three.js

While navigating a model with threejs pointerlock controls, clicking on specific sections of the model directs users to different parts of the site. However, an issue arises when the camera is centered over a section and the user exits the pointerlock. Upon re-entering the pointerlock mode, not only is the mouse trapped, but the event handler is triggered, sending the user elsewhere.

To resolve this issue, the event handler needs to be removed. Despite attempting to do so in the code, it doesn't seem to work as intended. The following snippet defines the bounding box of the clickable area and attaches the listener:

for (var p = 0; p < panels.length; p++ ) {
    // Relevant code block
}

The specific section responsible for adding or removing the window listener is highlighted here:

if (controls.isLocked) {
    console.log ('controls locked');
    window.addEventListener( 'click', function () {
        window.location.href = panels[p].url;
    }, false );
} else {
    console.log('controls unlocked');
    window.removeEventListener( 'click', function () {
        window.location.href = panels[p].url;
    });
}

The challenge lies in correctly invoking the removeEventListener. If I am doing it right, is there a way to ensure its proper functionality?

Answer №1

Your code snippet demonstrates adding and removing different functions based on a condition:

if (controls.isLocked) {
    console.log('controls locked');
    window.addEventListener('click', function () {

        // Execute this function when event occurs
        window.location.href = panels[p].url;

    });
} else {
    console.log('controls unlocked');
    window.removeEventListener('click', function () {

        // A different function is executed for event removal
        window.location.href = panels[p].url;

    });
}

To successfully remove an added event listener in the future, store the original function reference in a constant:

const originalFunction = function () {

    window.location.href = panels[p].url;

};

if (controls.isLocked) {
    console.log('controls locked');
    window.addEventListener('click', originalFunction);
} else {
    console.log('controls unlocked');
    window.removeEventListener('click', originalFunction);
}

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

How can Vue be used to dynamically change the input type on focus?

What Vue method do you recommend for changing an input element's type on focus? e.g. onfocus="this.type = 'date'" I am specifically looking to switch the input type from text to date in order to utilize the placeholder property. ...

The typical initial default argument to be passed to the function using fn.apply

Recently, I discovered the power of using fn.apply() in JavaScript to store function calls with all their arguments intact for future use. In my specific situation, I don't require the first argument, which is the context (this), and I want to find a ...

Tips for showing validation message just one time along with multiple error messages

Exploring ways to implement a dynamic form submit function using jQuery. $('#btnsumbit').click(function() { $('.required_field').each(function() { if ($(this).val() == "") { alert('please fill field'); ret ...

Troubleshooting an issue in Chrome with animating the "d" value using Snap.svg

To uncover the issue, try opening in both Chrome and Safari browsers. The logo animation should animate one section at a time like it does in Safari, but in Chrome, the animation seems to freeze. Check out the Snap.svg function responsible for running th ...

What steps should I take to grant API access if cross-browser requests are restricted?

Creating a C# web service to retrieve data from a server raises the question of how to grant API access to other users who want to query it using client-side code. For example, imagine the web service is hosted on Domain1.com. How can someone from Domain2 ...

Encountering an issue when implementing a conditional check within the .map() function utilizing ES6 syntax

I'm struggling to assign only the object that contains an iban value to the list in the code snippet below. I haven't been able to fix this issue on my own and would appreciate some assistance. This.ibanList = this.data.map( (value, in ...

Refreshing express-session sessions

My goal is to enhance the user experience by retrieving their profile from the mongodb database when they visit the page, and then updating their session with this information. Currently, I am utilizing the following packages for managing sessions: - ex ...

Exploring the Canvas with Full Element Panning, Minimap Included

Currently, I am working on incorporating a mini map onto my canvas that mirrors what is displayed on the main canvas. The main canvas includes zoom and pan functions. I have created a rectangular shape for the minimap to display the content of the canvas. ...

Encountering a white screen while loading StaticQuery on Gatsby website

I encountered an error that has been reported in this GitHub issue: https://github.com/gatsbyjs/gatsby/issues/25920. It seems like the Gatsby team is currently occupied and unable to provide a solution, so I'm reaching out here for help. Just to clar ...

The Vue2 @click event does not function properly when using v-html within a different component

I currently have a sign up form that includes an Alert component for displaying any errors. One of the conditions may prompt a message saying "You already have an account, click here to log in". The error messages are passed as props to the "Alert" compon ...

ScriptManager is not accessible in the current ASP.Net Core Razor Page context

I'm facing an issue where I have a view (such as Index.cshtml) and a page model (like Index.cshtml.cs). In the view, there's a JavaScript function that I want to call from the OnPost() method in the page model. I tried using ScriptManager for thi ...

What methods can I use to adjust the selected option according to the value in the database?

To introduce you to my work, I have a table filled with data from a database that functions as a CRUD - Create, Read, Update, Delete table. Within this table, there is a column where EDIT and DELETE buttons are located. Clicking on the EDIT button trigger ...

Tips for attaching a load event to an image

Although I am aware that $('img').load(function(){}) can function properly, I am interested in having the img dom that has not been initially created also be able to trigger the event. I am curious as to why the following code snippet does not wo ...

Retrieve data from a div element on a webpage using specific parameters

As I work on a form that includes various filters and a "Start" button in C# / ASP.NET MVC, my goal is to display database data in a partial view using Ajax when the button is clicked, based on certain parameters. Within this partial view, there is a link ...

It appears that the flex-grow property is not functioning as expected

I am working with a parent div and two children divs underneath it. I noticed that when I set the flex-grow property of the first child to zero, its width remains constant. However, if I add text to the second child, the width of the first child decreases. ...

What causes Express Async Errors to produce unexpected outcomes?

I stumbled upon a fantastic npm package called Express Async Errors that is highly recommended in the documentation. However, when I try to implement it, my server crashes. Here is my Route handler code: Controller const { Genre } = require("../models"); ...

The console.log() displays the dictionary correctly, but trying to access it with a key results in it being undefined

I'm currently facing an issue with accessing the dictionary stored in the "workload" field of a document in Firestore. Here is the snippet of code I am struggling with: async addTask() { const projectDoc = await getDoc(doc(db, "projects", "Testing ...

Populate your HTML with JSON data

I need some guidance on how to achieve a specific task. I have a PHP file that retrieves data from a MySQL database and returns it in JSON format. Now, I want to display this data in HTML with "data_from_json" replaced by "18.5". Any assistance would be gr ...

Combine all possible pairings of elements from two distinct arrays

Is there a way to combine the elements of two arrays and return them in a new array? Let's say we have these two arrays: const whoArr = ["my", "your"]; const credentialArr = ["name", "age", "gender" ...

I am experiencing issues with utilizing Array Filters in my Node.js backend when working with MongoDB

Utilizing it with Node.js in my backend. Encountered the following query: db.conversations.update( { convoId: convoId }, { $set: { "ids.$[elem].read" : true } }, { arrayFilters: [ { "elem.id": userId } ] }, (err, data) => { if(err) { ...