Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining if mouse click happened in left or right half of DIV

I was wondering if it's possible to calculate if a mouse click happened over the left or right half of the div element:

$("div").click(function(e){
 // calculate if click happened on left or right half
});


<div>Variable Content</div>

Was hoping there would be a way to get the relative coordinates and relate them to the width of the div?

like image 960
TGH Avatar asked Mar 28 '13 15:03

TGH


People also ask

How can you tell if a mouse is left or right jQuery?

Using the mousedown() method: The mousedown() method in jQuery can be used to bind an event handler to the default 'mousedown' JavaScript event. This can be used to trigger an event. The event object's 'which' property can then used to check the respective mouse button.

How do you tell the difference between click and drag?

The basic difference between a click and a drag event is the 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” event remains the same for both click and drag.

Can you click on a div?

The answer is definitely yes, but you will need to write javascript code for it. We can use a click handler on the div element to make it clickable.


1 Answers

$("div").click(function(e){
   var pWidth = $(this).innerWidth(); //use .outerWidth() if you want borders
   var pOffset = $(this).offset(); 
   var x = e.pageX - pOffset.left;
    if(pWidth/2 > x)
        $(this).text('left');
    else
        $(this).text('right');
});

DEMO: http://jsfiddle.net/dirtyd77/QRKn7/1/

Hope this helps! Let me know if you have any questions!

like image 155
Dom Avatar answered Sep 20 '22 16:09

Dom