GOTO 0
GOTO 0

Reputation: 47702

Detect if a mouse event occurred inside an element's client area

What is the proper way in Javascript to detect if a mouse event has occurred inside or outside an element's client area?

I have a container with a border and a scrollbar that serves as a control group. I would like to programmatically focus the active element in the group when the user clicks anywhere inside the container's client area but not when they click on the scollbar.

Upvotes: 2

Views: 3751

Answers (3)

Nux
Nux

Reputation: 10012

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.

Upvotes: 8

GOTO 0
GOTO 0

Reputation: 47702

I figured out how to do that. The code below is probably only going to work on newer browsers that support getBoundingClientRect.

function isMouseEventInClientArea(event)
{
    var element = event.currentTarget;
    var rect = element.getBoundingClientRect();
    var minX = rect.left + element.clientLeft;
    var x = event.clientX;
    if (x < minX || x >= minX + element.clientWidth) return false;
    var minY = rect.top + element.clientTop;
    var y = event.clientY;
    if (y < minY || y >= minY + element.clientHeight) return false;
    return true;
}

Upvotes: 1

rahul maindargi
rahul maindargi

Reputation: 5635

Here is working example http://jsfiddle.net/kYC9u/ and below is code snippet. Hope this helps

    <button onclick="doSomething('param');" id="id_button">action</button>
    <button onclick="doSomething('param');" id="id_button1">action2</button>




function doSomething(param,e)
        {
         if (!e)  e = window.event;
        var source1 = e.target || e.srcElement;
            console.log(source1.id);
        alert(source1.id);
        if(window.event) // IE8 and earlier
            {
            //doSomething
            }
        else if(e.which) // IE9/Firefox/Chrome/Opera/Safari
            {
            //doSomething
            }

        }

Upvotes: 0

Related Questions