Stop clicks from interfering with dragging in three.js

My GLTF model in Three.js has objects within it, and I want the camera to zoom in on an object when the user clicks on it. However, I am facing an issue where if the user drags after clicking on an object, a click is triggered upon releasing the mouse button, causing the camera to zoom in again. I tried using a "dragged" variable with nested if statements to solve this problem, but it's not working as expected. Can anyone suggest a solution?

var mesh=[];

const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2()

function onClick(event) {
    event.preventDefault();

    mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
    mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;

    raycaster.setFromCamera( mouse, camera );

    var intersects = raycaster.intersectObjects( scene.children, true );

    var dragged = false
    window.addEventListener('mousedown', function () { dragged = false })
    window.addEventListener('mousemove', function () { dragged = true })
    window.addEventListener('mouseup', function() {
        if (dragged == true) { return }
        //Click Tree006 to focus
    if ( intersects.length > 0 && intersects[0].object.name==="Tree006") {
        var object = intersects[0].object;
        zoomInTimeline(mesh["Tree006"].position.x, mesh["Tree006"].position.y, mesh["Tree006"].position.z, 5);

    console.log( 'Intersection:', intersects[ 0 ] );
    }

    //Click anywhere outside of object to leave focus
    if ( intersects.length > 0 && intersects[0].object.name!=="Tree006") {
        var object = intersects[0].object;
        gsap.to( camera.position, {
            duration: 1, // seconds
            x: 6,
            y: 4,
            z: 4,
            onUpdate: function() {
                controls.enabled = true;
                // controls.enableRotate = true;
                
            }
        } );
    }

    //Click object to focus
    if ( intersects.length > 0 && intersects[0].object.name==="Tree001") {
        var object = intersects[0].object;
        zoomInTimeline(mesh["Tree001"].position.x, mesh["Tree001"].position.y, mesh["Tree001"].position.z, 5);
    
    console.log( 'Intersection:', intersects[ 0 ] );
    }

    //Click anywhere outside of object to leave focus
    if ( intersects.length > 0 && intersects[0].object.name!=="Tree001") {
        var object = intersects[0].object;
        gsap.to( camera.position, {
            duration: 1, // seconds
            x: 6,
            y: 4,
            z: 4,
            onUpdate: function() {
                controls.enabled = true;
                // controls.enableRotate = true;
                
            }
        } );
    }
})
}

Answer №1

To understand this process in a step-by-step manner:

  1. The user initiates a click by pressing down on the mouse.
  2. While keeping the mouse button pressed, the user moves the cursor.
  3. If the user releases the mouse without moving it, it is registered as a click; if they release it after moving, it becomes a drag action.
let isDragging = false;
let isMouseDown = false;

window.addEventListener('mousedown', function () {
    isMouseDown = true;
});
window.addEventListener('mousemove', function () {
    if(isMouseDown) {
        isDragging = true;
    }
});
window.addEventListener('mouseup', function() {
    // If not dragging, treat it as a click
    if(!isDragging) {
        // Perform all actions for a click event here
    }

    // Reset flags
    isMouseDown = false;
    isDragging = false;
});

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

JavaScript code to retrieve an image from an <img> tag's source URL that only allows a single request and is tainted due to cross-origin restrictions

I have an image displayed in the HTML DOM. https://i.stack.imgur.com/oRgvF.png This particular image (the one with a green border) is contained within an img tag and has a URL as its source. I attempted to fetch this image using the fetch method, but enc ...

Images are failing to render on Next.js

Hello there! I am facing an issue while working on my Next.js + TypeScript application. I need to ensure that all the images in the array passed through props are displayed. My initial approach was to pass the path and retrieve the image directly from the ...

Developing a custom styling class using JavaScript

Looking to create a custom style class within JavaScript tags. The class would look something like this: #file-ok { background-image: url(<?php echo json.get('filename'); ?>); } Essentially, the value returned from the PHP file (json ...

Create an HTML table to view JSON data from a cell on a map

Looking to transform the JSON data into a table by organizing the information based on supplier and product. Below is the JSON input and code snippet: $(document).ready(function () { var json = [{ "Supplier": "Supplier1", "Product": "O ...

Ordering and displaying data with AngularJS

Trying to maintain a constant gap of 5 between pagination elements, regardless of the total length. For instance, with $scope.itemsPerPage = 5 and total object length of 20, we should have 4 pages in pagination. However, if $scope.itemsPerPage = 2 and tota ...

implementing ng-grid to showcase json information within an angularjs application

Recently I started learning Angularjs and I am looking to showcase the JSON data retrieved from a webservice response in a grid format using ng-grid. Here is my code snippet: function TestController($scope, $http) { alert("test"); $http({ url: &apos ...

The imgAreaSelect plugin is up and running successfully. Now, I am looking to utilize the x and y coordinates to make updates to the image stored in the database. How can I

After retrieving the dimensions and coordinates from the jQuery plugin imgAreaSelect, I am looking for guidance on how to update the image in my database based on this selection. The database contains a tempImage and Image field, and my goal is to allow ...

What is the best way to implement a dynamic sidebar component using React and Material UI?

I have been attempting to implement a responsive sidebar using React Material Design, but I am struggling to achieve the desired outcome. The main goal is for the page content to remain responsive when the sidebar is opened, without overlapping on the pag ...

Can anyone help me get my carousel to work properly?

I am facing a carousel problem in my personal exercise project. I have gathered HTML, CSS, and JavaScript from the internet and am attempting to integrate them all together. //Sidebar script start $(document).ready(function () { var trigger = $(&apo ...

Make a call to a remote node.js server using an ajax request

My setup involved a basic nodejs server (including CORS) : var express = require('express'); var app = express(); var http = require('http').Server(app); var io = require('socket.io')(http); var port = 8001; http.listen(port, ...

As a newcomer to Javascript, I am currently working on developing a CRUD-based application and could use some assistance with implementing the Edit functionality

I am currently in the process of developing a Javascript CRUD application that showcases data within an HTML Table. I have successfully implemented the Create, Read, and Delete functions. However, for the Edit function, I am looking to display the data in ...

Having trouble getting the npm package with @emotion/react and vite to function properly

Encountering an issue with the npm package dependencies after publishing, specifically with @emotion/react. This problem arose while using vite for packaging. Upon installing the package in another project, the css property appears as css="[object Ob ...

Using node.js version 10.0.0 to tinker with gulp

I was working on a node.js api project that functioned perfectly with node.js v8.1.4 & npm v5.0.3. However, upon transitioning to node.js v10.0.0 & npm v5.6.0, I encountered the following error: [email protected] ecosystem E:\opensource& ...

Is it possible to use CSS to create a gap between the cursor and the placeholder text within an input field?

Could you please assist me with a bug I have encountered on an older version of Firefox for OSX (37.0.2)? I have included a screenshot of the issue here: Is there a way to use css to move the first character of the placeholder text away from where the cur ...

Failed to retrieve the item stored in the local storage

I am encountering an issue where I am unable to retrieve an item from local storage and display it. In store.js, I am trying to get the shippingAddress from local storage but it is not showing up in the form. Although I am able to set the shippingAddress i ...

Angular app sends a JSON request and receives no data in response

It seems like Angular may be loading the page before fully receiving all the information from JSONP. There are times when refreshing the page multiple times eventually displays the information, but it's not consistent. Interestingly, the code used on ...

What could be the reason for my array parameter not being included in the POST request

When working on my laravel 5.7 / jquery 3 app, I encountered an issue while trying to save an array of data. After submitting the form, I noticed that only the _token parameter is being sent in the POST request as seen in the browser console: let todos_co ...

Managing a digital timepiece within a multiplayer gaming environment

I'm currently developing a fast-paced game where players control a block resembling a clock. To accurately calculate the time taken by each player to make moves, I store the start time of the game and record the timestamp of every move in the databas ...

Having trouble accessing a React component class from a different component class

I just started learning reactjs and javascript. For a simple project, I'm working on creating a login and registration form. The issue I'm facing is that when a user enters their email and password and clicks 'register', instead of movi ...

Is it possible to perform a legitimate POST request using AJAX XMLHttpRequest, rather than the traditional var=val URL type post?

Apologies for the unclear question, but here is my query... I recently began using Ajax and encountered an issue with sending XMLHttpRequest in the background. I am facing problems with certain html special characters in the form data, especially the & ...