Reputation: 949
Okay, "splitting" may not be the right word, I want one div that if your mouse is on the left half to perform one function and if your mouse is on the right hand side to perform an opposite function.
Before I setup two additional divs within the main div and used mouseover to achieve this, however I needed to place the z-index of the two dividing divs on top of the main div. The problem is, I need to add a click function to the main div that has several images inside (it is a rotating carousel).
Is is possible to divide the main div so that if the mouse is on one side it performs one action and the opposite on the opposite side using pageX or another function?
Upvotes: 0
Views: 193
Reputation: 318182
It's possible, and not really that hard either.
Just get the elements position relative to the document, and subtract that from half the width of the element, and compare it against e.pageX
, like so:
$('#test').on('click', function(e) {
var Dleft = $(this).width() / 2,
Cleft = e.pageX - $(this).offset().left;
if (Cleft > Dleft) {
$(this).html('You clicked the right half');
}else{
$(this).html('You clicked the left half');
}
});
Upvotes: 2
Reputation: 28316
I don't think you can have a different handler called based on mouse position within the element. But your handler can be passed the event object that will contain the mouse position, so you can do a quick comparison to determine which half the mouse is currently in and branch your code accordingly.
Upvotes: 0