![]() ![]() ![]() To get the caret coordinates, we, first of all, get the selection from the window object. If we have those, we can display a div that has a position: absolute attribute and a proper top and left positioning. Therefore, we need to know the X and Y coordinates of it. In the mentioned example, I wanted to show a context menu right above the caret. The Solution(s) Get The Caret Coordinates That makes it even harder.įortunately, we can solve both issues easily. Besides, editable elements can have nested HTML elements inside (e.g. If you use an input or textarea element, it is relatively easy to get that information because you have a selectionStart and selectionEnd attribute available on the form element itself.īut for contenteditable elements you do not have these attributes. ![]() To do that, we need to know the exact position of the caret. To adjust the styling of the content, I wanted to display a context menu right above the cursor. Recently, I built a text-editor where users could edit HTML content inside a contenteditable element. In this article, we are going to create two methods for locating the caret: One to get the X/Y coordinates and another to get the index position within the content. But since I struggled a lot with this issue in my latest project, I decided to share my approach - hoping that it might help one or the other. Yes, I know… there are certainly more exciting topics to write about than dealing with cursors on a web page. You can find this working example at the end of this article. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |