Javascript - Get element after carriage in child elements [contenteditable]

I am creating a simplified and easy-to-use text editor in Javascript, mostly a WYSIWYG editor. I will use the contenteditable attribute for the main shell ( .wrapper ). When you press enter inside .wrapper , a new new <p> element with a unique id added to the wrapper.

I need a way to select the child .wrapper element that is currently selected (i.e. focused or has a cursor / text marker inside it).

I searched for days without any results, and I tried using document.elementFromPoint() , but without any correct results.

When using $(":focus") I get the whole .wrapper , not the specific child.

Edit:

HTML structure example:

 <div class="container t-wrapper" contenteditable> </div> 

Javascript Code Example:

 $(document).ready(function() { $currentElement = $("[contenteditable]"); $(".t-wrapper").each(function() { var id = generateIdentifier(6); // Ignore this /* This creates the initial <p> child element, where you start typing. */ $(this).html('<p class="t-empty t-first" id="' + id + '"></p>'); $(this).on("mouseup", function() { /* $currentElement = whatever element the caret is inside. */ }); $(this).on("keyup", function() { /* $currentElement = whatever element the caret is inside. */ }); )); }); 

Edit 2:

I managed to get it to work with the mouseup event, since you are actually clicking on something. But I need this to work when moving the caret using the keyboard . In addition, I need to somehow get the position of the caret in pixels, and then use document.elementFromPoint() to get a specific element.

+5
source share
2 answers

:focus does not select your elements because they do not focus.

You can make them focused by adding tabindex="-1" in HTML or tabIndex = -1 in JS.

 var generateIdentifier = Math.random; var currentElement = document.querySelector("[contenteditable]"); [].forEach.call(document.querySelectorAll(".t-wrapper"), function(el) { var first = document.createElement('p'); first.className = "t-empty t-first"; first.id = generateIdentifier(6); first.textContent = 'Press enter to create new paragraphs'; first.tabIndex = -1; el.appendChild(first); }); 
 .container > :focus { border: 1px solid blue; } 
 <div class="container t-wrapper" contenteditable></div> 

It seems that if you add it to the first paragraph, the new paragraphs will get it automatically. But if you want to be sure, I think you could use a mutation observer or keyup event listener to detect paragraphs without tabindex and add it:

 el.addEventListener("keyup", function(e) { var newChild = el.querySelector('p:not([tabindex])'); if(newChild) newChild.tabIndex = -1; }); 
+2
source

document.activeElement will return the current focused element.

-1
source

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


All Articles