Recommended:

  • phpclasses.org
  • jsclasses.org
  • jsmag.com
  • siteapps.com
  • View our reviews on Hot Scripts
  • JS Tutorial
  • scripts.com
  • securesignup.com




Recent Comments

Powered by Disqus




Back to articles

Get relative cursor positions

Every browser support clientX and clientY mouse event properties to get cursor position relative to screen you see. If you'd like to get cursor position relative to whole page (counting scrolling position), it could be done using this function:

function get_page_coord(e)
{
    //checking if pageY and pageX is already available
    if (typeof e.pageY == 'undefined' &&  
        typeof e.clientX == 'number' && 
        document.documentElement)
    {
        //if not, then add scrolling positions
        e.pageX = e.clientX + document.body.scrollLeft
            + document.documentElement.scrollLeft;
        e.pageY = e.clientY + document.body.scrollTop
            + document.documentElement.scrollTop;
    };
    //return e which now contains pageX and pageY attributes
    return e;
}

And this function helps you to find cursor position inside any element with specfied width and height:

function get_elem_coord(e, elem)
{
    //checking if pageY and pageX is already available
    if (typeof e.pageY == 'undefined' &&  
        typeof e.clientX == 'number' && 
        document.documentElement)
    {
        //if not, then add scrolling positions
        e.pageX = e.clientX + document.body.scrollLeft
            + document.documentElement.scrollLeft;
        e.pageY = e.clientY + document.body.scrollTop
            + document.documentElement.scrollTop;
    };
    //temporary variables
    var x = y = 0;
    //check context of current element's offset position
    if (elem.offsetParent)
    {
        x = elem.offsetLeft;
        y = elem.offsetTop;
        //loop through all position contexts 
        //and sum up their positions
        while (elem = elem.offsetParent)
        {
            x += elem.offsetLeft;
            y += elem.offsetTop;
        };
    };
    //subtract contexts from from actual position 
    //to calculate relative position
    e.elemX = e.pageX - x;
    e.elemY = e.pageY - y;
    
    //return e which now contains pageX and pageY attributes
    //and provided elements relative position elemX and elemY
    return e;
}

You may also be interested in:

Powered by BlogAlike.com

blog comments powered by Disqus