Rich text editor wrap text with contenteditable - javascript

I'm trying to design a simple rich text editor using the contenteditable feature and need some help with this function that wraps the selection with tags (eg: <em>)
Example:
I start with this
<div contenteditable="true" id="editor">123<strong>abc</strong>xyz</div>
Selects a some text
3<strong>abc</strong>x
and then click on the button that executes the tag wrapping function.
<div contenteditable="true" id="editor">12<em>3<strong>abc</strong>x</em>yz</div>
How can I find the starting and ending of the selection to insert the opening and the closing tags?
I've been stuck for hours, any help would be great.

Try this:
var italicize = function () {
document.execCommand('italic');
};​
Just call this method whenever you wish to italicize the selected text.
See fiddle - http://jsfiddle.net/UdPAC/12/

Related

Focus on next paragraph in contenteditable div / Summernote

I am using Summernote but replicating the Medium editor.
When inserting images, I only allow them to be inserted into their own paragraph tag. No text can be mixed in side paragraph tags with an image.
I give each paragraph with an image inside a class of 'has-image'. What I now want to do it not allow the user to enter any text inside of the paragraph if it has that class.
If they try to click inside the tag it will instead focus to the next paragraph.
Any help how to do this? I have tried triggering a click on the next paragraph but no luck:
$(document).on('click', '.has-image', function() {
$(this).next('p').click();
});
I can set the text of the next paragraph so I know its selecting fine but cant think of a way to actually place the cursor inside.
JSFiddle as example: http://jsfiddle.net/vXnCM/5583/
U may need to work with Range
$(document).on('click', '.has-image', function() {
r = document.createRange()
r.setStart($(this).next('p')[0],0);
window.getSelection().removeAllRanges();
window.getSelection().addRange(r);
});
NOTE: It only works for most modern browsers except IE.
For IE capability, Check https://code.google.com/archive/p/ierange/

How can a DIV act like another element in Javascript?

My skills in Javascript are limited and for practicing i'm trying to programatically fill some elements using JS code, using Chrome's Developer Tools. I navigate to a site, access the console and try to manipulate DOM elements using JS code.
Usually elements a user can input data are INPUT, TEXTAREA , SELECT and so on. But latelly i've been seeing elements that are user-editable, but are simply DIVs. In other words, a DIV acting like an INPUT or TEXTAREA, and this got me confused.
Here is an example : i extracted this source from a page to post topics in a Facebook Group.
Note that the div that has the 'Write something' innerhtml works as a textarea in the page. You can reproduce this code in any Facebook Group, ie https://www.facebook.com/groups/914737511952904/ (you might need to join the group before see the box to post a topic).
<div class="_1mwp _1mwq _5bu_ _5yk1"><div class="_5yk2" tabindex="-2">
<div class="_5rp7">
<div class="_1p1t">
<div class="_1p1v" id="placeholder- 2bc29">Write something... </div>
</div>
</div>
</div>
If this element was a TEXTAREA, i could easily do something like
document.getElementById('elementId').value = 'New text';
But the 'textarea' element in the above case is actually a DIV and nothing else.
How can i insert text on it using JS ? An how can a DIV act like a textarea or an input ?
Thanks !
How can I insert text on it using JS?
That's quite simple. Just use the innerHTML property to assign the text value.
document.getElementById('elementId').innerHTML = "Text inserted"
However you can do the same using just CSS, and then retrieving the text from the div invoking the same property.
How can a DIV act like a textarea or an input?
A very practical way is using the contentEditable property over the div, but you can use CSS styles as well, and in some cases with some JavaScript code.
You have a simple example here using CSS styles and contentEditable property:
https://jsfiddle.net/ThinkingStiff/AbKTQ/
How can I insert text on it using JS?
element.textContent = "text content"
SNIPPET 1
var div = document.querySelector('div');
div.textContent = "line of text by textContent"
<div></div>
An how can a DIV act like a textarea or an input?
You can add contneteditable to an element that's not originally editable.
<div contenteditable></div>
See Snippet on how to set contenteditable by JS
SNIPPET 2
var editor = document.querySelector('div');
editor.setAttribute('contenteditable', true);
<div>This is a div. Click on me and start typing.</div>

Jquery get and set css attribute of some part of html string

I'm writing an html editor control.
I want to change css attributes of selected text of the content.
I get the selectedcontent by window.getSelection();
What is the best way to make bold selected text, and to understand selected text is bold then to make it normal.
Replace with required tags doesn't work. Since similar texts can be in content.
It looks quite complicated to me.
I'm looking for the best practise to do it.
Try this sample snippet
You can make bold as selected text via "document.execCommand('bold');"
Html
<div contenteditable="true" class="textEditor">Text1.
Text2.
Text3.
Text4.
Hi, this is text of some kind
Lorem ipsum...
</div>
Jquery
Catch selection change event by jquery-selectionchange event.
Make bold and normal by document.execCommand('bold');
$(document).on('selectionchange', function(e) {
document.execCommand('bold');
});
JsFIddle:
http://jsfiddle.net/XCb95/132/

Paste html from textarea to Contenteditable Div

I'm developing a RTE(rich text editor) using a wrapper div.
<div id="myeditor"></div>
//then
editorfunction(myeditor);
What the function does is add the following elements
<div id="myeditor">
<div class="toolbar">buttons here</div>
<div class="editorwrapper">
<div class="editor-richtext">
rich text etc
</div>
<textarea class="editor-source"><p>rich text etc</p></textarea>
</div>
</div>
I can successfully grab the html from the .editor-richtext and put it inside the textarea, but when I edit the textarea, I don't seem to be able to paste that back into the rich-text.
Thanks in advance!
Update 1
Ok, it seems that
$("richtext").blur(function() {
$("textarea").val($(this).html());
});
Works fine, but not the other way around (from textarea to richtext).
Update 2
It seems it is very unstable, it partially works but is acting strange :\
I'm not able to fully get content from textarea and paste as html into contenteditable. I will continue to do some research.
Update 3
I just updated update 1 and update 2 as I totally flipped textarea and richtext in my brain. Sorry!
Update 4
Ok, I pretty much got it solved now. I just have one slight problem, upon initialization, if I don't focus the contenteditable div and switch to the source view\textarea. the textarea is emptied, and when I then go back to RTE view\contenteditable div it is emptied. from the empty textarea\source.
I'm working on a work-around.
You can hook the onBlur event of textarea to copy the text and paste it in editor-richtext
$("textarea.editor-source").blur(function(){
$("div.editor-richtext").html($(this).val());
});
EDIT
For other way around, you can use the following code segment
$("textarea.editor-source").focus(function(){
$(this).val($("div.editor-richtext").text());
});
You may want to use jQuery and the following functionnalities?
$(".editor-source").keyup(function() {
$(".editor-richtext").html($(this).val());
});
Everything works fine. Selectors in your example are incorrect thought:
HTML:
<div class="editor-richtext">
original text
</div>
<textarea class="editor-source">modified text</textarea>
JS:
$(".editor-source").blur(function() {
$(".editor-richtext").html($(this).val());
});​
Demo
UPD:
$(".editor-richtext").click(function(){
$(".editor-source").val($(this).html().trim());
});
​
new demo that puts content from div into textarea on click event.

Wrap highlighted text within textarea with strong tags using javascript/jquery

I am looking to create a javascript/jquery function to wrap a piece of highlighted text from a textarea in strong tags - similar to the WYSIWYG editor here.
Is this possible and if so can you point me in the right direction.
EDIT:
OK so here's a hopefully clearer description of what I want...
I have a textbox on my page which I can type in.
I then want to be able to highlight a part of this text and wrap the highlighted part in <strong> tags
So if the text box had the words one two three and I highlighted the word "two", I want to be able to wrap that word in the strong tags - so becoming one <strong>two</strong> three
Hope this is clearer... I know there are plugins out there but I don't need the full WYSIWYG functionality.
My Rangy inputs (terrible name, I know) jQuery plug-in does this.
Example code:
$("#foo").surroundSelectedText("<strong>", "</strong>");
jsFiddle: http://jsfiddle.net/aGJDa/
I love Rangy! Use it often! But I didn't want to include the whole thing just for this little application, so I did it using document.execCommand to wrap the selected text, then used the href (third parameter of the CreateLink execCommand) to find the element, wrap it with what I wanted, and then remove the link:
document.execCommand('CreateLink', false, 'uniqueid');
var sel = $('a[href="uniqueid"]');
sel.wrap('<strong />')
sel.contents().unwrap();
document.execCommand is supported by all major browsers so you should be safe hacking it this way. In the browsers I've tested, the browser itself will close and open tags for you, so if you're selecting from the middle of one html tag to the middle of another, it should nest the tags correctly.

Categories