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?
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.
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.
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.
$("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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With