Actually instead of using clientWidth
etc you can just use other properties of the rect
. This makes the code simple and is more universal (should work for SVG elements too):
/**
* Check whether the event occurred roughly inside (or above) the element.
*
* @param {MouseEvent} event Event to check.
* @param {Node} element Element to check.
*/
function isEventInElement(event, element) {
var rect = element.getBoundingClientRect();
var x = event.clientX;
if (x < rect.left || x >= rect.right) return false;
var y = event.clientY;
if (y < rect.top || y >= rect.bottom) return false;
return true;
}
Note that getBoundingClientRect
works even for transformed element and also works with scroll (and with zoom if your are on mobile). And browser support is very good for the basic properties (see MDN).
You could also add some margin to support bigger tap areas.