Question

How do you capture the location of a cursor via an event listener?

In other words, if my user clicks a button, is it possible to find the location of the cursor at that time? If so, how?

UPDATE I am not sure if I was clear enough. I don't want the mouse location. What I meant to say is that if a cursor is inside an input field on a form, I want to locate the cursor and find out where the FOCUS is.

Était-ce utile?

La solution

Of course, when you click on a button, the focus is gone from anywhere else it was. But I seem to understand you want to know where the focus was just before.

You could so something like:

$('input, textarea, select').on('focus', function() { 
  console.log($(this).attr('id') + ' just got focus!!');
  window.last_focus = $(this).
});

$('button').on('click', function() {
  console.log('Last focus was on ' + window.last_focus.attr('id'));
});

This is just a very naive implementation. I am also very curious why you would need this?

There is also a focusout event which is triggered when something loses the focus, which might be more appropriate.

Autres conseils

$("#button").click(function(e){
  console.log(e.clientX)//relative screen
  console.log(e.clientY)
  console.log(e.pageX)//relative document(scroll + window position)
  console.log(e.pageY)
})

This should do the trick: http://jsfiddle.net/eTsN3/

$('button').click(function (e) {
    alert(e.pageX + '/' + e.pageY);
});

Further details: http://docs.jquery.com/Tutorials%3aMouse_Position

If you want to capture mouse location with Jquery and store it inside some tag use :

$(document).mousemove(function(e){
     $('#sometag').html("X Axis : " + e.pageX + " Y Axis : " + e.pageY);

  });

The mouse location info is supported by e.pageX and e.pageY. So in your case you can use

$('button').click(function(e){
         $('#sometag').html("X Axis : " + e.pageX + " Y Axis : " + e.pageY);

      });

You can read this

You can find out which input field currently has the focus with:

$("input:focus")

However, this won't work when you click on a button, because clicking outside the input field blurs it before running the click handler for the clicked handler. See this fiddle where I demonstrate it. It uses preventDefault(), but this doesn't prevent the blurring.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top