Search code examples
javascripteventsidentifier

Event Identifiers - ClientX and ClientY


I am trying to better understand the usage of the event attribute clientX and clientY.

I need to find the top and left offset of the mouse pointer when it moves over a particular div . The projectImage(x) function is attached to the onmouseover of the div. x is a function argument based on which the URL of a particular image can be determined.

Now. clientX is the left offset of the pointer at the time the mouseover event happens, so what can I enter for event in event.clientX

Th function below does not work (Reported as Not Defined by the JS Console) I think because of a syntax error in the first two lines.

function projectImage(x)
{

// Should the 1st two lines (right hand side) be x.clientY and x.clientX, 
// x is a function argument not event relevant to the pointer offset though

    var toffset = x.clientY ; // help_me_here.clientY

    var loffset = x.clientX ; // Event_Identifier_??.cleintX    

    var picdiv = document.getElementById("picdiv") ;
    picdiv.style.position = "absolute" ;
    picdiv.style.left = loffset + "px" ;
    picdiv.style.top = toffset + "px" ; 
    picdiv.innerHTML = "<img src='" + "http://imageServer.com/" + x.split("|")[1] + "' width='30px' />" ;

    picdiv.style.visibility = "visible";

}

Solution

  • As @FelixKling mentions you should be passing the event object.

    I recommend switching to addEventListener/attachEvent instead of using inline events as well, I set you up an example here.

    var x = document.getElementById('x');
    var y = document.getElementById('y');
    document.getElementById('test').addEventListener('mousemove', function(e){
        x.innerHTML = 'X: ' + e.clientX;
        y.innerHTML = 'Y: ' + e.clientY;
    });​
    

    If you're dead set on inline events, though, you can do it via <div onmouseover="projectImage(event,'Joey|123');"> Joey </div>