When the design mode is on of an iframe body then if we press the enter key we a div is appended to the document body like this:
<body>
<div><br/></div>
</body>
Which is pretty much good for my use case as i am working on a text editor with a support for code block and blockquote along with bold,italics,underline.
My approach to apply Blockquote and CodeBlock is that i have defined a CSS and would add the classes to the
respective div/code element
In order to apply the classes on the div, i need to know that where exactly is my caret at . So for example i am in the body and added some text for blockquote then how can i know at which child element (div) holds my text to be formatted.
What I have tried:
var editor = document.getElementById("rtf-iframe").contentWindow.document.body;
editor.document.designMode = 'On';
var editor = document.getElementById("rtf-iframe").contentWindow.document.body;
I tried it via a click, whenever i click on the editor i can get the position of the child clicked :-
var currentLineClicked;
function setIndexOfClicked() {
for (var i = 0, len = editor.children.length; i < len; i++)
{
(function(index){
editor.children[i].onclick = function(){
currentLineClicked =index;
console.log("clicked div index is :"+currentLineClicked);
}
})(i);
}
}
After that i can successfully add a class to this div :
function applyBlockquote(){
var currentIndex = currentLineClicked;
console.log(editor.children[currentIndex]);
editor.children[currentIndex].className = "bquote";
}
But what if a user adds some extra children in the body by pressing enter ? I tried playing with the
MutationObserver to detect what kind of changes are being done in the Node but couldn't find how to get the current position of the caret/cursor ?
var targetNode = document.getElementById('some-id');
var config = { attributes: true, childList: true, subtree: true };
var callback = function(mutationsList, observer) {
for(var mutation of mutationsList) {
if (mutation.type == 'childList') {
console.log('A child node has been added or removed.');
}
else if (mutation.type == 'attributes') {
console.log('The ' + mutation.attributeName + ' attribute was modified.');
}
}
};
var observer = new MutationObserver(callback);
observer.observe(targetNode, config);
observer.disconnect();
A very close reference/example to my idea is this
Markdown Editor :
I can see that a hidden text area is being used here.
(Image of Inspected Element)