Get X, Y coordinates when opening a key using JavaScript / jQuery


I am developing a rich text editor. I want to open the user context menu when the user presses the ctrl+space key at the position where the event is fired.
I do not get event coordinates. Is it possible to get the coordinates of the event?
Here is my sample code

 <!DOCTYPE html> <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script> <style> #edit{ border:1px solid red; width:500px; height:300px; } #ctxMenu{ display: none; position: absolute; border: 1px solid #000000; } #ctxMenu ul li{ list-style: none; } </style> </head> <body> <div id="edit" contenteditable="true"> </div> <div id="ctxMenu"> <ul> <li>One</li> <li>Two</li> <li>Three</li> <li>Four</li> </ul> </div> <script> $('#edit').keydown(function(e){ /**** get x, y coordinates. * */ if (e.ctrlKey && e.keyCode == 32) { $('#ctxMenu').show().css({left:x,top:y}); } }); </script> </body> </html> 
+4
source share
4 answers

HERE-JSFIDDLE is the result for your CODE.

OR

JS CODE (just replace the js code with the code below.)

 $(document).ready(function(){ $('#edit').bind('keydown', function(e){ var $this = $(this); var a = $this.data('mousepos').x; var b = $this.data('mousepos').y; if (e.ctrlKey && e.keyCode == 32) { $('#ctxMenu').show().css({left:a,top:b}); }else{ $('#ctxMenu').hide(); } }); $('#edit').bind('mousemove', function(e){ $(e.target).data('mousepos', {x: e.pageX, y: e.pageY}); }); }); 
+1
source

To get x, y keyboard events:

 $('#edit').keydown(function(e){ var $target = $(e.target); var x = $target.offset().left; var y = $target.offset().top; if (e.ctrlKey && e.keyCode == 32) { $('#ctxMenu').show().css({left:x,top:y}); } }); 
+1
source

Perhaps caret () is what you are looking for (pageX and pageY will not work for a div); The following link may help:

jQuery: get cursor position of text in input without browser code?

if you want to use the coordinates of the document, you can use the following, but it will respond to keystrokes anywhere on the page, and not just in the text box (if you use a div instead, e.pageX will be undefined)

 $(document).keypress(function(e) { var code = (e.keyCode ? e.keyCode : e.which); if (e.ctrlKey && code == 32) { alert(e.pageX); // for y use e.pageY } }); 
0
source

@Tim, it does not work if there is no text after the cursor position. Maybe we insert an element into the cursor and find out that this will work? I use it in IE 8, and I found that the x and y positions are zero. I have editable content div with text like "one two". Now, if my cursor is somewhere between the text, I get the values, but if it moves after both both are zero. The input element and then the search also no use.Any comments?

0
source

Source: https://habr.com/ru/post/1485778/


All Articles