The Wayback Machine - https://web.archive.org/web/20241123044535/https://www.geeksforgeeks.org/how-to-differentiate-mouse-click-and-drag-event-using-javascript/
Open In App

How to differentiate mouse “click” and “drag” event using JavaScript ?

Last Updated : 28 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Working with web elements a user may drag or click an element as per requirement. It is important to distinguish between drag and click events. JavaScript is a high-level, dynamically typed programming language that can be used to distinguish between drag and click events. JavaScript has drag-and-clicking events that help to differentiate between the two. This article demonstrates two methods of differentiating between click and drag events. In the first method, we will display the output on the console whereas, in the second approach, we will display the output on the webpage itself. The user can choose either method at his convenience.

These are the following approaches:

Approach 1: Using mousedown, mousemove, mouseup events

We have a web page where any kind of click or drag event is logged in the console. The basic difference between a click and a drag event is mouse movement. The mouse event that differentiates a click and drag event is the “mouse move” event. In a “click” event, there is no “mouse move” event. However, the “mouse down” and “mouse up” events remain the same for both click and drag. 

The JavaScript code below shows that a variable named drag is initiated with a ‘false‘ boolean value. For the “mouse down” event, ‘the drag‘ variable remains false. But as soon as a “mouse move” event is triggered the drag variable is set to ‘true‘. On the “mouse up” event, the value of the drag variable is checked. If the value is true, a “drag” event has occurred and the output is displayed in the console. If the value is ‘false‘ it means there has been no “mouse move” event which also implies that a “click” event had occurred. Hence the click output is displayed in the console.

Example: This example shows the above-explained approach.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
 
<body>
    <script type="text/javascript">
        let drag = false;
        document.addEventListener(
            'mousedown', () => drag = false);
 
        document.addEventListener(
            'mousemove', () => drag = true);
 
        document.addEventListener(
            'mouseup', () => console.log(
                drag ? 'drag' : 'click'));
    </script>
</body>
 
</html>


Output: On click and drag events, the output is displayed in the console as shown below.

Approach 2: Using ondrag and onclick

The second approach is element specific and does not work for all the other elements in the web page. We choose an element to log the “click” or “drag” events. In the example below, a paragraph is chosen as the required element and we assign ‘draggable‘ and ‘clickable‘ attributes as true which means the element can be dragged as well as clicked.

The JavaScript events ondrag and onclick help us achieve the desired result. When the element is clicked, a click message is displayed just below the element on the web page itself. When the element is dragged, a drag message is displayed just below the element in the web page itself. The click and drag events are fired as per the user activity and then the actions corresponding to the events are executed.

Example: This example shows the above-explained approach.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
 
<body>
    <p id="dragtarget" draggable="true" clickable="true">
        Click Me or Drag Me!
    </p>
 
    <p id="demo" style="color:red;"></p>
 
    <script type="text/javascript">
        document.ondrag = function (event) {
            document.getElementById("demo").innerHTML
                = "Element is being dragged";
        };
 
        document.onclick = function (event) {
            document.getElementById("demo").innerHTML
                = "Element is being clicked!";
        };
    </script>
</body>
 
</html>


Output:



Previous Article
Next Article

Similar Reads

How to attach a click and double-click event to an element in jQuery ?
In this article, we will see how to attach a click and double-click event to an element in jQuery. To attach click and double-click events, click and dbclick events are used. These events are attached with the bind() method. This method is used to attach one or more event handlers for selected elements and this method specifies a function to run wh
1 min read
How to distinguish left and right mouse click using jQuery?
jQuery can be used to distinguish which mouse button is being clicked. This can be used in various web applications where knowing a certain mouse button can be used to trigger certain functionality. Using the mousedown() method: The mousedown() method in jQuery can be used to bind an event handler to the default 'mousedown' JavaScript event. This c
2 min read
How to create a pop-up div on mouse over and stay when click using jQuery ?
In this article, we will learn how to create a pop-up div on mouseover and stay when click using jQuery. Approach: First, we create an HTML div element that we want to pop up when we mouse over on an element and set its display property to none in CSS style.display:none;In the script tag, we create a variable flag and set its value to -1. $flag = -
2 min read
Javascript Drag and Drop event - error catching
Javascript Drag and Drop event allows users to drag and drop elements within a web page. The event is initiated when the user clicks on an element and drags it to a new location. There are several other types of errors that can occur when working with the drag-and-drop event in Javascript. Here are a few examples: "Cannot read property 'setData' of
4 min read
Difference Between @click and v-on:click in VueJS
Vue. JavaScript allows programmers to "hook" events into HTML elements using these unique event directives. One of them is the v-on directive, which is used to listen for certain events (clicks) and then run a method when that event occurs. v-on:click is the full version of the command that binds a click event to an element. That makes it obvious t
3 min read
How to get the coordinates of a mouse click on a canvas element ?
The coordinates of the mouse whenever a click takes place can be found by detecting the click event with an event listener and finding the event's x and y positions. In this article we are going to learn How to get the coordinates of a mouse click on a canvas element. ApproachCreate a JavaScript function getMousePosition that takes the canvas eleme
2 min read
jQuery UI Dialog Drag Event
jQuery UI Drag event is triggered when the dialog box is dragged. Learn more about jQuery selectors and events here. Syntax: $(".selector").dialog ( drag: function( event, ui ) { console.log('dragged') },Approach: First, add jQuery Mobile scripts needed for your project.<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-u
1 min read
jQuery UI Draggable drag Event
jQuery UI is a web-based technology and consists of various GUI widgets, visual effects, and themes. These features can be implemented using the jQuery JavaScript Library. jQuery UI is the best tool for building UI interfaces for the webpages. It can also be used to build highly interactive web applications or can be used to add widgets easily. In
2 min read
How to add click event to Google Map markers stored in an array in JavaScript ?
To add a click event to markers stored in an array, you will first need to iterate over the array of markers using a loop. Then, within the loop, you can bind a click event to each marker. Syntax: var markers = [marker1, marker2, marker3]; // Array of markersfor (var i = 0; i < markers.length; i++) { // Bind a click event to the current marker m
3 min read
How to programmatically fire a click event for a file input element in JavaScript ?
In this article, we will learn how to programmatically fire click events on the input file element. ApproachWhenever you want to perform a click event programmatically, at your specific condition, just use the JavaScript in-built click() function by DOM object. Example: document.getElementById('your_input_type_file_element_id').click();Example 1: W
2 min read
Create a Drag and Drop Sortable List using HTML CSS & JavaScript
In this article, we will create a drag-and-drop sortable list using HTML, CSS, and JavaScript. This interactive feature will allow users to reorder items in a list by simply dragging and dropping them. Preview of final output: Let us have a look at how the final output will look like. Prerequisites to create Drag & DropHTMLCSSJavaScriptApproach
3 min read
Build A Drag & Drop Kanban Board using HTML CSS & JavaScript
A Kanban board is a project management tool designed to visualize work, limit work in progress, and maximize efficiency. With drag & drop functionality, users can easily move tasks between different stages of completion, providing a visual representation of the workflow. Approach:The below defined steps can be utilised to build and design a Kan
4 min read
How to Differentiate Functions Using Math.js?
Differentiation is a fundamental concept in calculus, used extensively in mathematics, physics, engineering, and many other fields. While traditional methods of calculus involve manual calculations, modern computing tools like math.js can simplify this process significantly. Math.js is a powerful, open-source library for mathematics that runs in Ja
2 min read
How to create a drag and drop feature for reordering the images using HTML CSS and jQueryUI ?
In this article, we are given an images gallery and the task is to re-arrange the order of images in the list or grid by dragging and dropping. The jQuery UI framework provides a sortable() function that helps in re-ordering list items by using the mouse. With this functionality, the list items become interchangeable. The jQuery UI provides a sorta
3 min read
What is the use of a double-click event in AngularJS ?
The ng-dblclick event in the AngularJS is useful for the HTML elements for getting the double click event, defined. In case a user wishes to get the function fired or other events when the double click of the HTML elements is done, then this event will be going to be needed. All the elements of the HTML will be going to support it. Basically, the d
2 min read
What's the effect of adding return false to a click event listener ?
Given a link with onclick() event and return statement and the task is to get the effect after clicking the event. Below is a code containing anchor element, onclick() event, and return statement. <a href='https://www.google.com' onclick='someFunc(3); return false;'> Click here ! </a> What is the effect of the return false to a click ev
2 min read
How to detect click event outside Angular component ?
In angular, clicks are detected by different ways. As click is an event, thus inside a component it is detected by simple event binding. A simple click via event binding for detection within the component is given as follows: @Component({ selector: "geeks", template: ` <h1 (click)="clicked()">{{ some_text }}</h1> ` }
3 min read
How to set a click event once a page or view is loaded in vue.js?
In this article, we will discuss how to set a click event once a page or view is loaded in vue.js. Just like every other JavaScript framework Vue also supports the Mounting hooks. Mounting hooks are often the most used hooks. They allow us to access or modify the DOM of your component just before or after the first render. So, here we will use the
2 min read
Vue.js Click Event
Vue.js is a progressive framework for building user interfaces. The core library is focused on the view layer only and is easy to pick up and integrate with other libraries. Vue is also perfectly capable of powering sophisticated Single-Page Applications in combination with modern tooling and supporting libraries. The v-on directive is used to let
2 min read
How to run a code on double-click event in jQuery ?
In this article, we will see how to run a code after double clicked the element using jQuery. To run the code on double clicked we use dblclick() method. This method is used to trigger the double-click event to occur. This method occurs when the selected element will be double clicked. Syntax: $(selector).dblclick(args); Parameter: It accepts an op
1 min read
How to run a code on click event in jQuery ?
In this article, we will see how to run the code after clicking on an event. To run the code after clicking an event, we use the click() method. The click() method is used to run the code when a click event occurs. The click() method to attach a click event handler to selected elements. Inside the handler function, you can define the code to be exe
1 min read
jQWidgets jqxNotification click Event
jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxNotification represents a jQuery widget that can be used to display some notification content to the user. It can be modified according to user needs. The cli
1 min read
jQWidgets jqxButton click Event
jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxButton is used to illustrate a jQuery button widget that enables us to show a button on the desired web page. The click event is activated whenever the displa
1 min read
jQWidgets jqxChart click Event
jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. jqxChart is a lightweight and powerful chart widget written 100% in JavaScript. It offers many advanced features and supports three different rendering technologies
2 min read
jQuery click() Method vs onClick Event
jQuery is the JavaScript library known for its lightweight, fast, and cross-platform features. It is an open-source library that goes by the motto "Write less, do more". The main objective of jQuery is to make Java script so easy that one can create more attractive and interactive websites. jQuery has multiple events like jQuery onClick(), jQuery c
5 min read
How to Create Button Dynamically with Click Event in Angular ?
The task is to create a button dynamically with a click event using AngularJS, i.e., whenever someone clicks on the button then a new button gets created. The easiest way to create a button in AngularJS is to use the ng-repeat directive. We can easily hook up a repeat logic inside a button click event by using the ng-click Directive. Syntax: <el
2 min read
How to call a function on click event in Angular2 ?
A Function is a set of statements that takes input, does some specific computation, and produces output. An on click event occurs when the user clicks on an element. In this article, we will see How to call a function on click event in Angular2, along with understanding the basic implementation through the examples. Setting the Angular Application
3 min read
Create Dynamic Table with Auto Increment Serial Number on Button Click Event
We will see how we can auto increment the serial number of a table in html using JavaScript. We will build a button clicking on that will add a row to a table with an increasing number of rows. It will show the dynamic behavior, showing that we will use JavaScript and jQuery. These are the following methods: Table of Content Using JavaScriptUsing J
3 min read
How to Create a Click Event on Pie Chart ?
Chart.js is an open-source free JavaScript library that is used to visualize data-informed charts like pie, lines, bars, scatter, and many more. Chart.js provides an onClick event feature by using it you can interact with specific segments of the pie chart. In this article, we will learn about how to create an onClick event in a pie chart. Approach
3 min read
How to add active class on click event in custom list group in Bootstrap?
In Bootstrap, adding an "active" class on a click event in a custom list group means dynamically applying the active class to a list item when it is clicked. This highlights the clicked item, making it visually distinct using Bootstrap's built-in styles for active states. Syntax: $(document).ready(function() { $('selector').click(function() { $('se
3 min read
three90RightbarBannerImg