Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript : how to insert tags around a text selection?

I want to create a little WYSIWYG HTML text editor with a contenteditable div.

For that, I use window.getSelection() to retrieve the selected text, and when I click in a button (button bold), I execute a function to add bold tags around the selected text.

But I don't have any idea about the javascript code (without JQuery) to add bold tags.

Here my code :

<input type="button" value="B" style="font-weight:bold;" onclick='add_tags("b");'>

<div id="container_contenteditable" class="container_contenteditable" contenteditable></div>

<script type="text/javascript">

function add_tags(tags)
{
    container_contenteditable = document.getElementById("container_contenteditable");

    //Retrieve the selected text :
    sel = window.getSelection();
}

</script>
like image 499
totoaussi Avatar asked Jan 30 '16 18:01

totoaussi


People also ask

Why would you surround a piece of text with tags?

In general, they make a document easier to read by breaking up a large document into smaller parts, each part having a heading that has different formatting (larger text, bold, etc.), than the rest of the document.

Which tag is used to show the inserted text?

Definition and Usage. The <ins> tag defines a text that has been inserted into a document. Browsers will usually underline inserted text.

How to use ins tag?

HTML <ins> Tag. The <ins> tag in HTML is used to specify a block of inserted text. The <ins> tag is typically used to mark a range of text that has been added to the document. The inserted text is rendered as underlined text by the web browsers although this property can be changed using CSS text-decoration property.

Can you use tags in JavaScript?

The <script> tag is used to embed a client-side script (JavaScript). The <script> element either contains scripting statements, or it points to an external script file through the src attribute.


2 Answers

It's actually simpler than you might think:

function add_tags(tags)
{
    document.execCommand('bold');
}
<input type="button" value="B" style="font-weight:bold;" onclick='add_tags("b");'>

<div class="container_contenteditable" contenteditable style="border:1px solid; margin: 10px 0; height: 100px;"></div>
like image 126
Daniel Avatar answered Nov 14 '22 22:11

Daniel


Writing your own editor is not that nightmare-ish - but it does require a lot of time, attention to detail and learning.

When I wrote mine I ended up converting all styling to spans - in the end it's easier and gives a consistency across browsers.

So with spans, you replace the current selection with (eg:) <span style="font-weight:bold">your selected text</span>

Works a treat...

like image 23
Tony Duffill Avatar answered Nov 14 '22 21:11

Tony Duffill