abidibo.net

Just Open Source

How to get the mouseovered half of an element

events javascript

You can also be interested in:

Today I'll write a very simple and short post about a very simple function that you can use to retrieve in which half (left/right) of an element the mouse is moving towards. The function is written in vanilla javascript, no frameworks are involved.

Given the element which captures the event and the event itself the function return the string 'left' or 'right' depending on the cursor position over the element.

/*
 * Gets the mouseovered half of an element
 * @param {Element} element: the element which captures the event
 * @param {Event} evt: the event object
 * @return the mouseovered half ('left' | 'right')
 */
var getMousemoveHalf = function(element, evt) {
  var element_coords = element.getBoundingClientRect(),
      pointer_coords = {x: evt.clientX, y: evt.clientY};
      // only gecko sets the widh property
      return pointer_coords.x < (element_coords.left + (element_coords.right - element_coords.left) / 2) ? 'left' : 'right';
}

All the magic is done by the getBoundingClientRect function, which has a good browser compatibility.

Subscribe to abidibo.net!

Special offer!

If you subscribe to this blog within the 7 of february 2016, you'll receive a discount code of 1€ that you can use to buy my first e-book "Your Smartwatch Loves Tasker", available for purchase here on abidibo.net at the price of 3.79€!


If you want to stay up to date with new contents published on this blog, then just enter your email address, and you will receive blog updates! You can set you preferences and decide to receive emails only when articles are posted regarding a precise topic.

I promise, you'll never receive spam or advertising of any kind from this subscription, just content updates.

* indicates required

abidibo.net topics

Comments are welcome!

blog comments powered by Disqus

Your Smartwatch Loves Tasker!

Your Smartwatch Loves Tasker!

Now available for purchase!

Featured