I am trying to process content content in an iframe so that browsers do not add br , p or div themselves when I press Enter. But something strange happens when you try to reset the focus, and it just works when creating a warning () before processing the rest of the code. I think this is because javascript needs some time to complete the operations, but there must be a way to do this without a "sleeping" script ...
Here I insert my code (working with JQuery), only with "magic Alerts" it works fine:
//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 delete Magic Alerts, it still works on Chrome, but in FF it focuses on the beginning of everything! (As if it were offset = 0)
UPDATE
Porblem seems to be a string that replaces newlines with br . If I delete this line, it works fine even without warning. I need to save br tags, is there any other way to do this?
javascript alert
Kenedy
source share