-1

Is there any way to get cursor position in custom function? I also know that the example bellow able to get the x and y.

$(".myelement").mousemove(function (e) {
    var y = e.pageY - $('.myelement').offset().top;
    console.log(y);
});

However my html is come from an ajax, so example is not working. So I was thinking about a custom function. But custom function not able to set an event, am I right? Is there any suggestion or other way to get cursor position in an element (div) ?

FeelRightz
  • 2,082
  • 1
  • 24
  • 55
  • `my html is come from an ajax, so example is not working` In this case you need to use a delegated event handler. See the question I marked as duplicate for a full explanation of the problem and several solutions. – Rory McCrossan May 19 '16 at 07:58

2 Answers2

1

However my html is come from an ajax, so example is not working.

This means the Element is added in dynamically into the DOM. To make Jquery work on the elements added dynamically we must make use of event delegation

$(document).on("mousemove",".myelement",function (e) {
        var y = e.pageY - $('.myelement').offset().top;
        console.log(y);
    });
Rajshekar Reddy
  • 17,202
  • 3
  • 34
  • 54
1

You simply need to delegate that event from a higher element, even possibly the document itself. That way it will work even for your dynamically loaded content.

Then you save the x andy position in a variable for use in your function

$(function(){

    var y;
    $(document).on('mousemove','.myelement',function(){
        y = e.pageY - $('.myelement').offset().top;
    });

    // use `y` elsewhere

});
Jamiec
  • 118,012
  • 12
  • 125
  • 175