abidibo.net

How to get the mouseovered half of an element

events javascript

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!

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.

Subscribe to this blog

Comments are welcome!

blog comments powered by Disqus

Your Smartwatch Loves Tasker!

Your Smartwatch Loves Tasker!

Now available for purchase!

Featured