1
votes

I want to display the mouse position when its inside an element.. heres the code:





Mouse Events Example


 function GetMousePositionInElement(ev, element)
           {
               var osx = element.offsetX;
               var osy = element.offsetY;

               var bottom = osy + element.height();

               var x = ev.pageX - osx;
               var y = bottom - ev.pageY;

               return { x: x, y: y, y_fromTop: element.height() - y };
           }
    function handleEvent(oEvent) {
        var oTextbox = document.getElementById("txt1");
        var elem = document.getElementById("div1");
        var xp = GetMousePositionInElement(oEvent, elem).x;
        var yp = GetMousePositionInElement(oEvent, elem).y; 

        oTextbox.value += "\n x = " + xp + "y= " + yp;

    }



Use your mouse to click and double click the red square.

div style="width: 100px; height: 100px; background-color: red" onmouseover="handleEvent(event)" id="div1"> /div

textarea id="txt1" rows="15" cols="50"> /textarea>

There is a problem in the code. Mouse position is not displayed inside the texArea. What changes do i have to make for the code to work and work correctly? (of-cource not all of the code is displayed and i removed some of the < and > inoder to show you some parts of the code that are not displayed otherwise but the code syntax is correct, thats not the problem)

Thank you.

1

1 Answers

1
votes

var osy = element.offsetY;

There's no such property as offsetY. You may be thinking of offsetTop. However note the offsetLeft/​Top values are relative to the offsetParent not the page. If you want page-relative co-ordinates you would need to loop through offsetParents, or, since you seem to be including jQuery, call its offset function that does just that:

var offset= $(element).offset();
var osx= offset[0], osy= offset[1];

var bottom = osy + element.height();

element is a DOM HTMLDivElement object, not a jQuery wrapper object, so it doesn't have the height() method. Either add the wrapper:

var bottom= osy+$(element).height();

or use the equivalent DOM method:

var bottom= osy+element.offsetHeight;

var y = bottom - ev.pageY;

Note pageY is not part of the DOM Events standard and also not available in IE. You can calculate it by using the standard clientY property and adjusting for the page's scrollTop. Again, jQuery does this for you, adding the Firefox pageY extension to all browsers, when you use its own methods to bind your event handler:

$('#div1').mouseover(handleEvent);

instead of the inline onmouseover=... event handler attribute.