Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Line Above or Below in Javascript

I am working on an in-place HTML editor, concentrating on Firefox only right now. I have an element inserted where the cursor should be and also have left and right arrows working, but I can't seem to find a way to find:

  1. Start and end of a line for the home and end keys
  2. The next line up or down for the up/down arrows.

I see document.elementFromPoint, but this doesn't get me a Range object. The Range object itself seems rather useless when it comes to using pixel positions.

like image 600
Dark Falcon Avatar asked Mar 22 '26 17:03

Dark Falcon


1 Answers

If you need a to create a range for the element under specific pixel position, you can combine document.elementFromPoint() and document.createRange() and Range.selectNodeContents();

The snippet below would highlight the content of an element at (100,200)

var elem = document.elementFromPoint(100,200);
var r = document.createRange();
var s = window.getSelection()
r.selectNodeContents(elem);
s.removeAllRanges();
s.addRange(r);

I hope this will help you find the final solution.

like image 64
SWilk Avatar answered Mar 24 '26 07:03

SWilk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!