unable to exit pointer lock controls in three.js

My code successfully locks the cursor, but I am struggling to unlock it when running a function. Here is my code:

var element = document.body;

var controls;
var instructions = document.getElementById( 'start' );
var havePointerLock = 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document;

if ( havePointerLock ) {


    var pointerlockchange = function ( event ) {

        if ( document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element ) {

            controlsEnabled = true;
            controls.enabled = true;

        } else {

            controlsEnabled = false;
            controls.enabled = false;

            instructions.style.display = '';

        }

    };

    var pointerlockerror = function ( event ) {

        instructions.style.display = '';

    };

    // Hook pointer lock state change events
    document.addEventListener( 'pointerlockchange', pointerlockchange, false );
    document.addEventListener( 'mozpointerlockchange', pointerlockchange, false );
    document.addEventListener( 'webkitpointerlockchange', pointerlockchange, false );

    document.addEventListener( 'pointerlockerror', pointerlockerror, false );
    document.addEventListener( 'mozpointerlockerror', pointerlockerror, false );
    document.addEventListener( 'webkitpointerlockerror', pointerlockerror, false );

    instructions.addEventListener( 'click', function ( event ) {

        instructions.style.display = 'none';

        // Ask the browser to lock the pointer
        element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock;

        if ( /Firefox/i.test( navigator.userAgent ) ) {

            document.addEventListener( 'fullscreenchange', fullscreenchange, false );
            document.addEventListener( 'mozfullscreenchange', fullscreenchange, false );

            element.requestFullscreen = element.requestFullscreen || element.mozRequestFullscreen || element.mozRequestFullScreen || element.webkitRequestFullscreen;

            element.requestFullscreen();

        } else {

            element.requestPointerLock();

        }

    }, false );

} else {

    instructions.innerHTML = 'Your browser doesn\'t seem to support my epic Portfolio';

}

When attempting to unlock the pointer lock controls using element.exitPointerLock;, no errors occur, but the mouse does not return. When using element.exitPointerLock();, I receive an error stating "element.exitPointerLock is not a function." Any suggestions on how to solve this issue would be greatly appreciated. If more code or a jsfiddle example is needed, please let me know :)

Answer №1

After some troubleshooting, I finally found the solution! Instead of using:

element.exitPointerLock();

I switched to:

document.exitPointerLock();

And now everything is functioning perfectly! Hopefully this tip can assist someone else as well :)

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

Upload file via AJAX immediately after downloading it (no need for storage)

Currently, I am in the process of developing a JavaScript script to safeguard an old game development sandbox website from being discarded by its owners. In order to prevent the loss of all the games on the site, I have managed to create a script that allo ...

How is it possible that my array becomes reversed without any intervention on my part?

As I work on developing a website, I encountered a puzzling issue with the calculations inside the router. Despite initializing the array tomato with the desired values, it seems that the values get reversed just before rendering the page. Here is the code ...

Tips for sending an extra parameter to the callback function when using the loader.parse method in Three.js

The Parse method of the Loader object in three.js allows you to specify a callback function that will be triggered upon completion of the parsing process. This callback will receive a unique argument which represents the parsed object. However, I am encou ...

Changing the color of each line within a BufferGeometry using Three.js

This example demonstrates drawing lines with the same color. I aimed to change the color of each line and here are the modifications I made: Introducing attribute const colors = new Float32Array(MAX_POINTS * 3); geometry.setAttribute('color' ...

Using async await in node.js allows you to bypass the need for a second await statement when

As I dive into using await async in my Node.js ES6 code... async insertIngot(body, callback) { console.log('*** ItemsRepository.insertIngot'); console.log(body); const data = await this.getItemsTest(); console.log('*** ge ...

What is the process for transforming JSON into a different format?

Currently, I have a JSON array structured as follows: var data = { report: [ { Name: "Nitin", comment: [ { count: 0, mName: "Feb" }, ...

Issue arises when there are several inline <script> tags containing parameters which result in filtered JSON output

As a newcomer to JavaScript, I am faced with the challenge of creating a centralized glossary within a confined educational environment (LMS) that lacks a database or any other facilitating elements. My objective is to develop a script hosted on our applic ...

react-responsive-carousel: setting a specific height for thumbnail images

After setting a fixed height for the image, I noticed that the same height is also being applied to the thumbnails. How can I avoid this issue? <Carousel width="600px" dynamicHeight={false}> {data?.book?.images.map((image, i) => ( ...

Remove an item from the options list in the select2 plugin after an event occurs

I am currently using the Select2 plugin in my project and I am facing an issue where I want to remove an option from the main list. However, when I click on the "x" button generated by the code, it only removes it temporarily from the plugin's list. U ...

The jQuery code continues to loop endlessly

My current script includes a fadeIn effect on a div when the user scrolls 200px from the top, along with custom circle animations. While it works, I admit it's not the most elegant solution as I had to piece together different scripts to make it funct ...

Utilizing jQuery TableSorter Scroller: How to Achieve Scrolling with Keydown Focus

Apologies for any language barriers. I am currently utilizing tablesorter 2.0 along with scroller functionality. On my page, the table scrolling function works when I interact with the table directly. However, I want the scrolling to happen automatically ...

The function L.featureGroup.subGroup() is a powerful tool provided by Leaflet and Cart

I'm struggling with getting the subgroups to function correctly. The clusters display, but when I deactivate layers, the clusters do not update accordingly. Moreover, activating a layer turns on all underlying points. How can I ensure that the subgrou ...

Using Angular 7 to trigger a file download from the server with proper Authorization

I'm facing some challenges while trying to implement a specific functionality with Angular 7 and I could use some assistance. Here's the scenario: We have a service that returns static files (PDFs), but it requires authorization to access the AP ...

Having trouble getting the Javascript dropdown script to work on a Wordpress page?

Hello all, I've been experimenting with creating a simple dropdown menu for my Wordpress website. The idea is that when a user clicks on a specific text, a dropdown menu with various links will appear. I followed the guidance from W3 Schools, but unfo ...

Scroll up and down to witness the enchanting interplay of fading in and out

Looking to expand upon the solution given in this response. The existing code effectively fades in an element while scrolling down and fades out an image when scrolling up; however, it lacks the functionality to fade out when scrolling down. I am aiming ...

Here is a unique version: "Learn how to efficiently transfer data from multiple parent elements to another page using the same buttons by leveraging LocalStorage

I received assistance from mplungjan to create part of the code. Currently, I have created multiple buttons for various paragraphs, functioning as favorite buttons. My goal is to transfer these favorited paragraphs to a different page. For more details, yo ...

Deactivate a button when clicked on a card that has been mapped

After creating a card component and mapping through each card, I added an onClick function to disable the button of the clicked card. However, my logic ended up disabling all buttons instead. Here is the code snippet where I define the rendering of the UI ...

How to Properly Implement app.use() in Express for Middleware

What is the reason behind some middleware functions being passed in with invocation parentheses, while an anonymous function is passed in without being invoked? app.use(logger()); app.use(bodyParser()); If logger() is evaluated immediately and the return ...

How to build a registration form with Stateless Components?

Could someone provide a sample code or explanation on how to create a form using stateless components? I'm also in need of a Material UI form example that utilizes refs. Please note that I am working with Material UI components. Below is the curren ...

What is the best way to showcase data in a table using React Js?

I'm working on a project in React Js where I need to display data fetched from an API in a table. The challenge is that the data is received as an object and I'm struggling to map through it efficiently. Currently, I have hardcoded some sample da ...