I am trying to handle a contenteditable body in an iframe, in order to prevent browsers from adding br
,p
or div
on their own when pressing Enter. But something weird happens when trying to reset the focus, and it just does work when making an alert() before processing the rest of the code. I think it is because javascript needs some time to make operations, but there must be a way to do it without "sleeping" the script...
Here I paste my code (working with Jquery), only WITH the "magic Alerts" it works perfectly:
//PREVENT DEFAULT STUFF
var iframewindow=document.getElementById('rte').contentWindow;
var input = iframewindow.document.body;
$( input ).keypress( function ( e ) {
var sel, node, offset, text, textBefore, textAfter, range;
// the Selection object
sel = iframewindow.getSelection();
alert(sel); //MAGIC ALERT
// the node that contains the caret
node = sel.anchorNode;
alert(node); //MAGIC ALERT
// if ENTER was pressed while the caret was inside the input field
if ( node.parentNode === input && e.keyCode === 13 ) {
// prevent the browsers from inserting <div>, <p>, or <br> on their own
e.preventDefault();
// the caret position inside the node
offset = sel.anchorOffset;
// insert a '\n' character at that position
text = node.textContent;
textBefore = text.slice( 0, offset );
textAfter = text.slice( offset ) || ' ';
node.textContent = textBefore + '\n' + textAfter;
SEEREF=SEEREF.replace(/\n/g, "<br>");
// position the caret after that newBR character
range = iframewindow.document.createRange();
range.setStart( node, offset + 4 );
range.setEnd( node, offset + 4 );
// update the selection
sel.removeAllRanges();
sel.addRange( range );
}
});
SEEREF = framewindow.document.body.innerHTML (it was too long)
Edit When I remove the Magic Alerts it still works on Chrome, but in FF it focuses on the beginning of all! (Like if it were offset=0)
UPDATE
It seems like the porblem is the line which replaces the newlines with br
tags. If I remove this line, it works perfectly even without the alerts. I need to keep this br
tags, is there any other way to do it?