Stop accidental clicks during dragging

I am currently utilizing Three.js to exhibit a 3D model that allows users to manipulate the camera by dragging and click on objects to zoom in. However, I am encountering an issue where the system registers a click and drag as a click, triggering the animation unintentionally. I am in need of a solution to prevent clicks from being registered during dragging, ensuring they are only recognized as clicks when there is no mouse movement involved.

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 );

    if ( intersects.length > 0 && intersects[0].object.name==="Tree006") {
        var object = intersects[0].object;
        gsap.to( camera.position, {
            duration: 1,
            x: mesh["Tree006"].position.x,
            y: mesh["Tree006"].position.y,
            z: mesh["Tree006"].position.z,
            onUpdate: function() {
                controls.enabled = false;
                camera.lookAt(0,0,0);
            }
        } );
        console.log( 'Intersection:', intersects[ 0 ] );
        
        
    }

    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: 6,
            onUpdate: function() {
                controls.enabled = true;
                camera.lookAt( 0,0,0 );
            }
        } );
    }


}

Answer №1

Click event will only be triggered once you release the mouse button over the specified element. To prevent any action from happening when the click event occurs, you can set a flag on mousedown and then reset it on mouseup.

var btn1 = document.querySelector("#btn1");
var flag = false;

btn1.addEventListener('click', function(ev) {
  if (!flag) {
    alert(1);
  }
  ev.preventDefault();
})


btn1.addEventListener('mousedown', function(ev) {
  flag = true;
  console.log("flag to disable click is true");
})

btn1.addEventListener('mouseup', function(ev) {

  // this is a temporary solution:
  setTimeout(function() {
    flag = false
    console.log("flag to disable click is false");
  });
})
<button id="btn1">no click</button>
<button id="btn2" onclick="alert(2)">click</button>

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

Utilizing a particular Google font site-wide in a Next.js project, restricted to only the default route

My goal is to implement the 'Roboto' font globally in my Next.js project. Below is my main layout file where I attempted to do so following the documentation provided. import type { Metadata } from "next"; import { Roboto } from "n ...

Styling text using SVG in HTML

I'm trying to underline a text element in SVG using the text-decoration attribute, but I'm running into an issue with the color of the line not changing. Here is the code snippet I am working with: <svg id="svg" viewBox="0 0 300 ...

Timer for searching webpages using Javascript

I am looking for a way to continuously search a specific webpage for a certain set of characters, even as the text on the page changes. I would like the program to refresh and search every minute without having to keep the webpage open. In addition, once ...

Steps for Building and Exporting a Next.js Project Without Minification and Optimization

Is there a way to build and export a Next.js project without minifying and optimizing the output files? ...

Exploring the directories: bundles, lib, lib-esm, and iife

As some libraries/frameworks prepare the application for publishing, they create a specific folder structure within the 'dist' directory including folders such as 'bundles', 'lib', 'lib-esm', and 'iife'. T ...

How do you populate a dropdownlistfor in ASP.NET MVC after a form

My issue is that <form> @Html.DropDownListFor(x => x.City, provinces, "--Select City--", new { @class = "dropdownList" }) @Html.DropDownListFor(x => x.district, Enumerable.Empty<SelectListItem>(), "--Select district--") < ...

The hyperlink does not function properly when included within an <input type=button> element

I have encountered an issue with the code below. In my project, I have a search bar along with some buttons. Currently, only the hyperlink of the search button is functioning correctly. The other buttons seem to redirect to the same link as the search bu ...

Using JavaScript, swap out the text enclosed in square brackets with an array

Changing the text inside square brackets with values from an array is my goal. For instance: <pre id="text"> [maybe] i should [leave] [to] help you [see] [nothing] is [better] [than] this [and] this is [everything] we need </pre> The transfo ...

There seems to be an issue with the transaction payload in the Cardano wallet when submitting an

I am attempting to send a previously signed transaction from cardano-cli using the cardano-wallet endpoint: https://localhost:8090/v2/proxy/transactions Here is how the signed transaction appears: txBody = { "type": "Tx MaryEra&q ...

Guide to importing OBJ file into three.js using TypeScript

Currently, I am utilizing TypeScript along with three.d.ts obtained from definitely typed. While I have successfully been using THREE.JSONLoader, I am encountering difficulties with implementing an OBJLoader from here in a TypeScript project. It seems th ...

Ways to exhibit API information leveraging the prowess of Ajax

I am looking for a way to utilize the API in order to present data in an organized manner, similar to the following example: Job Title: Agricultural and Related Trades Percentage of Occupancies in Area: 15.41% Unfortunately, my attempt to showcase the d ...

When a PHP-generated child element is clicked, jQuery fails to detect it

I'm currently developing a website where I need to dynamically display buttons based on database content. These buttons, when clicked, should send a request to the database and update the page content accordingly. My approach involves using Ajax and ...

Is there a way to extract the query string from a file in order to query the database using ExpressJS?

I am having trouble with this code snippet as it doesn't seem to be working properly. var content = fs.readFileSync('/home/diegonode/Desktop/ExpressCart-master/views/partials2/menu8xz.hbs', 'utf8' ); req.db.products.find( co ...

The code is running just fine when tested locally, but it seems to encounter an issue when accessed remotely, yielding

Currently, I am in the process of developing a dual twin setup using a Raspberry Pi. The goal is to simulate a continuous transmission of body temperature data, which is then sent to a server that stores the information in a MongoDB database. Everything fu ...

Unable to apply CSS styles to a form input using Ajax

Alright, so I've got this Ajax form that successfully fetches the data and displays it in #register_msg. However, I'm also trying to apply some styles to the input forms. Here's my Ajax code, along with the form. But for some reason, the st ...

How can I reset a CSS position sticky element using JavaScript?

I have created a page where each section fills the entire screen and is styled using CSS position: sticky; to create a cool layered effect. Check it out here: https://codesandbox.io/s/ecstatic-khayyam-cgql1?fontsize=14&hidenavigation=1&theme=dark ...

The property 'innerHTML' cannot be assigned to null, as stated in Vue

I am dealing with two components that allow for editing JSON objects. Additionally, I have a button that toggles between these two components. Below is the HTML code snippet: <v-btn @click="switchConfigClicked">Switch config</v-btn> <h4 cla ...

The Node.js Express Server runs perfectly on my own machine, but encounters issues when deployed to another server

I've encountered a strange issue. My node.js server runs perfectly fine on my local machine, but when I SSH into a digital ocean server and try to run it there, I get this error. I used flightplan to transfer the files to the new machine. deploy@myse ...

Unable to use jQuery to choose an item from a dropdown menu and reveal a hidden text box

Seeking assistance in displaying a paragraph with text and a textbox when a specific option is selected from the dropdown menu on my form. Previously used code for radio buttons, but encountering issues with this scenario. Any guidance would be greatly app ...

Having trouble with `request.auth.session.set(user_info)` in HapiJS?

I've encountered an issue with my strategy that is defined on a server.register(). Although I followed a tutorial, the code seems to be copied verbatim from it and now it's not functioning as expected. server.auth.strategy('standard&apo ...