I have some javascript that manipulates html based on what the user has selected. For real browsers the methods I'm using leverage the "Range" object, obtained as such:
var sel = window.getSelection();
var range = sel.getRangeAt(0);
var content = range.toString();
The content variable contains all the selected text, which works fine. However I'm finding that I cannot detect the newlines in the resulting string. For example:
Selected text is:
abc
def
ghi
range.toString() evaluates to "abcdefghi".
Any search on special characters returns no instance of \n \f \r or even \s. If, however, I write the variable out to an editable control, the line feeds are present again.
Does anyone know what I'm missing?
It may be relevant that these selections and manipulations are on editable divs. The same behaviour is apparent in Chrome, FireFox and Opera. Surprisingly IE needs totally different code anyway, but there aren't any issues there, other than it just being IE.
Many thanks.
Editing my post:
Experimenting a bit, I find that sel.toString() returns new lines in contenteditable divs, while range.toString() returns newlines correctly in normal non-editable divs, but not in editable ones, as you reported.
Could not find any explanation for the behaviour though.
This is a useful link http://www.quirksmode.org/dom/range_intro.html
I found at least two other ways, so you may still use the range to find the position of the caret in Mozilla.
One way is to call
var documentFragment = rangeObj.cloneContents ();
which holds an array of childNodes, and any line breaks will show as a node of class "HTMLBRElement".
The other way is to make sure every "br" tag is followed by a newline character (0x0a)!
This won't hurt the HTML content in any visible way, but now all HTML breaks are translated to plain text line breaks as soon as range.toString() is being called!
I hope this helps - even if this topic is very old. (I'm a necromancer anyway already, hehe) :)
Thanks to the OP I was able to do it using window.getSelection() as he suggested. I needed to get the text until the caret position on an InputEvent , which gives me a static range with the inserted text. So I have a range but not necessarily the current selection's range.
function richToPoorText(range){
//Caso base, está colapsado.
console.log(range);
var restoreRange=document.createRange(); //needed for restoring the caret pos.
restoreRange.setStart(range[0].endContainer, range[0].endOffset);
restoreRange.setEnd(range[0].endContainer, range[0].endOffset);
rangeClone=document.createRange();
rangeClone.setStart(__baseEditor,0);
rangeClone.setEnd(range[0].endContainer, range[0].endOffset);
var str;
var sel=window.getSelection();
sel.removeAllRanges();
sel.addRange(rangeClone); //sel does converts the br to newlines
str=sel.toString();
sel.removeAllRanges();
sel.addRange(restoreRange);
return str;
}
Thankyou very much OP. And if someone has the same use case, you can use this snipset
Edit: __baseEditor is a global variable pointing to the editor's main contenteditable div
Related
I'm surprised I'm having trouble with this and unable to find an answer. I'm trying to get the text in a contenteditable, from the start of the contenteditable to the users cursor/caret.
Here's a jsFiddle of what I've attempted (click around the contenteditable and watch console.log).
I get the caret location and then I attempt to get the content:
I tried using textContent of the contenteditable which works but if there's content like foo<br>bar it outputs foobar when ideally it should output foo\r\nbar (Note: This is for a chrome extension I have no control over the content of the contenteditable).
innerText works as expected outputting foo\r\nbar, but as can be seen in the jsFiddle once the html in contenteditable gets a little complex the caret position doesn't seem to match the location in innerText and I have trouble outputting up to the caret.
Found some code using the Range interface and modified it to meet my needs in this jsFiddle but had the same problem with <br> as textContent did.
Note: The user will continue typing as I get the content, so looking for something that doesn't break this flow.
Just looking for direction, any quick tips on what I should try?
In your fiddle I replaced the JavaScript content with:
document.querySelector("#edit").addEventListener("click", function(){
var target = document.querySelector('#edit');
var sel = document.getSelection();
if(!sel.toString()) {
var range = document.getSelection().getRangeAt(0);
var container = range.startContainer;
var offset = range.startOffset;
range.setStart(target, 0);
//do your stuff with sel.toString()
console.log(sel.toString());
//restore the range
range.setStart(container, offset);
}
});
Hope this helps.
Edit: since you said
Note: The user will continue typing as I get the content, so looking for something that doesn't break this flow.
I thought that the click event was just an example; getting the text while user is typing implies:
the entry point can't be click event but probably a setInterval function
while user is typing there is no selections, only the caret
To solve the reported bug is enough changing the code as I did, anyway this is only an example to get the result you are interested in; than you have to work on it to achieve the desired behavior for all the possible case of your real scenario.
I know there are other questions on editable divs, but I couldn't find one specific to the Markdown-related issue I have.
User will be typing inside a ContentEditable div. And he may choose to do any number of Markdown-related things like code blocks, headers, and whatever.
I am having issues extracting the source properly and storing it into my database to be displayed again later by a standard Markdown parser. I have tried two ways:
$('.content').text()
In this method, the problem is that all the line breaks are stripped out and of course that is not okay.
$('.content').html()
In this method, I can get the line breaks working fine by using regex to replace <br\> with \n before inserting into database. But the browser also wraps things like ## Heading Here with divs, like this: <div>## Heading Here</div>. This is problematic for me because when I go to display this afterwards, I don't get the proper Markdown formatting.
What's the best (most simple and reliable) way to solve this problem as of 2015?
EDIT: Found a potential solution here: http://www.davidtong.me/innerhtml-innertext-textcontent-html-and-text/
if you check the documentation of jquery's .text() method,
The result of the .text() method is a string containing the combined text of all matched elements. (Due to variations in the HTML parsers in different browsers, the text returned may vary in newlines and other white space.)
so getting whitespaces is not guaranteed in all browsers.
try using the innerText property of the element.
document.getElementsByClassName('content')[0].innerText
this returns the text with all white spacing intact. But this is not cross browser compatible. It works in IE and Chrome, but not in Firefox.
the innerText equivalent for Firefox is textContent (link), but that strips out the whitespaces.
This is what I've been able to come up with using that link I posted above in my edit. It's in Coffeescript.
div = $('.content')[0]
if div.innerText
text = div.innerText
else
escapedText = div.innerHTML
.replace(/(?:\r\<br\>|\r|\<br\>)/g, '\n')
.replace(/(\<([^\>]+)\>)/gi, "")
text = _.unescape(escapedText)
Basically, I'm checking whether or not innerText works, and if it doesn't then we do this other thing where we:
Take the HTML, which has escaped text.
Replace all the <br> tags with line breaks.
Strip out any tags (escaped ones won't be stripped, i.e. the stuff the user types).
Unescape the escaped text.
When the user edits a contenteditable div, and press some keys, I would like to override the default behavior.
For instance, I want to insert a normal line break when the user press ENTER.
I do that using document.execCommand("insertText",...)
This is the only way I have found so far to make this action undoable and redoable by the user.
<div id="editor" contenteditable="true" style="white-space:pre-wrap">
Some text....
</div>
<script>
$("#editor").keydown(function(evt){
console.log(evt.keyCode);
if(evt.keyCode==13){
document.execCommand("insertText",false,"\n");
evt.preventDefault();
evt.stopPropagation();
}
}
</script>
This code works well on chrome and firefox. But, ie does not support "inserttext". Would there be a way to insert text with ie, such that the user can undo it?
IE 11 has new ms-beginUndoUnit and ms-endUndoUnit commands.
I tried and failed to create a working solution for IE 11 using these. Inserting a line break is hard with DOM ranges and selections; you can do it more easily in IE using its legacy document.selection and TextRange objects but unfortunately IE 11 removed document.selection (but not TextRange, strangely) which makes it difficult. After coding a nasty workaround to create a TextRange from the selection, undo didn't work anyway. Here's what I did:
http://jsfiddle.net/E7sBD/2
I decided to have another go using DOM Range and selection objects. The line break insertion code is illustrative and shouldn't be used for anything serious because it involves adding a non-breaking space to give the caret somewhere to go (trying to place it directly after the <br> does not work). Undoing does remove the inserted content but unfortunately doesn't move the caret.
http://jsfiddle.net/E7sBD/4/
You can always go the simpler and more stable way to catch the change event on the input div and change the last char from the input string to your liking.
http://api.jquery.com/change is invented i think for that purpose :)
Change your angel and you see a whole new world :3
I have a <textarea> that I want to grow by one row every time the user enters into the last row shown in the <textarea>. Is this possible?
I have seen it done before, but can't figure out how to do it.
Okay, I just created this off the top of my head, so there may be browser compatibility issues. The concept is pretty simple however. Basically, on every keyup event, append a newline to the current text in the textarea element, then check if scrollHeight is greater than offsetHeight. If this is the case, set the elements height to be equal to scrollHeight. After all this, remove the appended newline. Assuming your textarea element has the id ta:
EDIT -- Okay, my original idea caused the cursor position to jump to the end of the text even if the user moved the cursor back, not good. The fix I came up with involves creating an invisible clone of the text area, and inserting the extra newline in that one, as to not disturb the cursor position in the visible one. Not sure I'm enterily comfortable with this method, but it works for now. If there is a better method I'd be happy to hear it. Here's the updated code:
var shadow = document.createElement('textarea');
shadow.className = 'autosize';
shadow.style.visibility = 'hidden';
document.getElementById('ta').onkeyup = function() {
this.parentNode.appendChild(shadow);
shadow.value = this.value + '\n';
if (shadow.scrollHeight > shadow.offsetHeight) {
this.style.height = shadow.scrollHeight + 'px';
}
this.parentNode.removeChild(shadow);
};
And the updated test http://jsfiddle.net/7wezW/1/
Now back to your regular programming...
Works well in Chrome, if someone points out issues in other browsers, I will try work them out.
PS, I should point out that if the user pastes text using just the mouse, the size of the textarea element will not adjust. Should be a trivial issue, but I'll leave it out as not to over-complicate things.
There are code and a demo at http://webdesign.torn.be/tutorials/javascript/prototype/auto-expand-contract-textarea/.
There's also a non-IE6 version that doesn't use frameworks:
http://scrivna.com/blog/2008/04/12/javascript-expanding-textareas/
Yes, there are many plugins for JQuery, such as this one, which comes with a demo: http://james.padolsey.com/javascript/jquery-plugin-autoresize/
Very customizable in terms of maximum height, buffer space, etc.
I am working on an in-place HTML editor, concentrating on Firefox only right now. I have an element inserted where the cursor should be and also have left and right arrows working, but I can't seem to find a way to find:
Start and end of a line for the home and end keys
The next line up or down for the up/down arrows.
I see document.elementFromPoint, but this doesn't get me a Range object. The Range object itself seems rather useless when it comes to using pixel positions.
If you need a to create a range for the element under specific pixel position, you can combine document.elementFromPoint() and document.createRange() and Range.selectNodeContents();
The snippet below would highlight the content of an element at (100,200)
var elem = document.elementFromPoint(100,200);
var r = document.createRange();
var s = window.getSelection()
r.selectNodeContents(elem);
s.removeAllRanges();
s.addRange(r);
I hope this will help you find the final solution.
I'm not sure what you mean by 'start and end of a line'. Are you referring to a line of text on the page, regardless of its containing element? Can you provide a link to your app or an illustrative example page?
IE and Firefox both provide an element.getClientRects() method. However, it only works under certain circumstances and doesn't behave the same from browser to browser. See quirksmode for details.
This method will probably not be helpful in many situations. In the case that you have a P element containing bare text, Firefox returns a collection containing a single element representing the P element. It doesn't tell you anything about the lines of text it contains.
Most of the in-place editors that I've seen work by clicking on an element to edit it. The element is then replaced by a textbox/area and associated save/cancel buttons.