Rendering HTML inside textarea

293,167

Solution 1

This is not possible to do with a textarea. You are looking for a content editable div, which is very easily done:

<div contenteditable="true"></div>

jsFiddle

div.editable {
    width: 300px;
    height: 200px;
    border: 1px solid #ccc;
    padding: 5px;
}

strong {
  font-weight: bold;
}
<div contenteditable="true">This is the first line.<br>
See, how the text fits here, also if<br>there is a <strong>linebreak</strong> at the end?
<br>It works nicely.
<br>
<br><span style="color: lightgreen">Great</span>.
</div>

Solution 2

With an editable div you can use the method document.execCommand (more details) to easily provide the support for the tags you specified and for some other functionality...

#text {
    width: 500px;
    min-height: 100px;
    border: 2px solid;
}
<div id="text" contenteditable="true"></div>
<button onclick="document.execCommand('bold');">toggle bold</button>
<button onclick="document.execCommand('italic');">toggle italic</button>
<button onclick="document.execCommand('underline');">toggle underline</button>

Solution 3

Since you only said render, yes you can. You could do something along the lines of this:

function render(){
	var inp     = document.getElementById("box");
	var data = `
<svg xmlns="http://www.w3.org/2000/svg" width="${inp.offsetWidth}" height="${inp.offsetHeight}">
<foreignObject width="100%" height="100%">
<div xmlns="http://www.w3.org/1999/xhtml" 
style="font-family:monospace;font-style: normal; font-variant: normal; font-size:13.3px;padding:2px;;">
${inp.value} <i style="color:red">cant touch this</i>
</div>
</foreignObject>
</svg>`;
	var blob = new Blob( [data], {type:'image/svg+xml'} );
	var url=URL.createObjectURL(blob);
	inp.style.backgroundImage="url("+URL.createObjectURL(blob)+")";
 }
 onload=function(){
  render();
  ro = new ResizeObserver(render);
	ro.observe(document.getElementById("box"));
 }
#box{
  color:transparent;
  caret-color: black;
  font-style: normal;/*must be same as in the svg for caret to align*/
  font-variant: normal; 
  font-size:13.3px;
  padding:2px;
  font-family:monospace;
}
<textarea id="box" oninput="render()">you can edit me!</textarea>
This makes it so that a textarea will render html! Besides the flashing when resizing, inability to directly use classes and having to make sure that the div in the svg has the same format as the textarea for the caret to align correctly, it's works!

Solution 4

Try this example:

function toggleRed() {
  var text = $('.editable').text();
  $('.editable').html('<p style="color:red">' + text + '</p>');
}

function toggleItalic() {
  var text = $('.editable').text();
  $('.editable').html("<i>" + text + "</i>");
}

$('.bold').click(function() {
  toggleRed();
});

$('.italic').click(function() {
  toggleItalic();
});
.editable {
  width: 300px;
  height: 200px;
  border: 1px solid #ccc;
  padding: 5px;
  resize: both;
  overflow: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="editable" contenteditable="true"></div>
<button class="bold">toggle red</button>
<button class="italic">toggle italic</button>

Solution 5

An addendum to this: You can use character entities (such as changing <div> to &lt;div&gt;) and it will render in the textarea.

But when it is saved, the value of the textarea is the text as rendered. So you don't need to de-encode. I just tested this across browsers (Internet Explorer back to version 11).

Share:
293,167

Related videos on Youtube

The Coding Monk
Author by

The Coding Monk

Artificial Intelligence and Robotics student. Programmer, IT enthusiast, and many other things. Follow me on Twitter @TheCodingMonk

Updated on May 09, 2022

Comments

  • The Coding Monk
    The Coding Monk about 2 years

    I need to be able to render some HTML tags inside a textarea (namely <strong>, <i>, <u>, <a>) but textareas only interpret their content as text. Is there an easy way of doing it without relying on external libraries/plugins (I'm using jQuery)? If not, do you know of any jQuery plugin I could use to do this?

    • Pointy
      Pointy over 13 years
      The only way to do that will be to overlay your HTML markup over the content of the textarea tag via CSS positioning tricks. Nothing will help you convince the browser to render the textarea contents differently. (Why exactly do you "need" to do this?)
    • The Coding Monk
      The Coding Monk over 13 years
      I just need the user to be able to add some formatting styles to the text he enters (much like when you write an article on Wordpress). I just do not need all the features like text alignment and so on, but only those basic tags.
  • Ben
    Ben almost 11 years
    its a real shame that you can't practically use this without the use of javascript to either submit your changes using ajax or copy them into a form input. If anyone has found a way to do it i'd be really interested!
  • Tim Down
    Tim Down almost 11 years
    @yckart: Well, I don't think that's actually valid, even though it works in all browsers I've tried. contenteditable is an enumerated attribute rather than a Boolean attribute (there's an inherit state as well as true and false) , and I think that means that specifying a value is mandatory, although I can't find a definitive bit of the spec to confirm this. MDN seems to agree though.
  • Tim Down
    Tim Down almost 11 years
    @yckart: I'm not 100% sure though. The fact that <div contenteditable></div> works in all browsers does make me wonder :)
  • yckart
    yckart almost 11 years
    @TimDown I've fiddled a bit around and it seems that contenteditable without true or false doesn't inherit from its parent, as MDN says: jsbin.com/eqelip/1/edit
  • Tim Down
    Tim Down almost 11 years
    @yckart: I'd assumed the browser interprets contenteditable with no value as being the same as contenteditable="", which in turn is the same as contenteditable="true".
  • mekwall
    mekwall almost 11 years
    @TimDown That's exactly how it's interpreted. However, I think it's a rather bad practice to omit the value, even though it works.
  • Matt Ellen
    Matt Ellen about 10 years
    This doesn't work any better than a textarea. Typing <strong>someting</strong> into the fiddle leaves you with that exact text. The HTML is not applied.
  • mekwall
    mekwall about 10 years
    @MattEllen contenteditable turns the element into a rich text editor, so you can use ctrl+b and ctrl+i to make text bold or italic. It does not parse HTML though, that you'll have to deal with yourself, like this.
  • sirdank
    sirdank over 8 years
    I would really like for this to work for me but it didn't. For example <textarea> check for url &lt;B&gt;http://localhost/Dashboard.aspx&lt;/B&gt; &lt;BR&gt; Tool Started at &lt;B&gt;11/10/2015 3:56:58 AM&lt;/B&gt; &lt;BR&gt; .... </textarea> does not display as HTML. I'm on Chrome 46.
  • axlotl
    axlotl over 8 years
    Hm. I copy-pasted that string directly into an html document and it renders the markup properly for me in Chrome Version 48.0.2552.0 dev (64-bit) OS X 10.11.1. So maybe it's a version problem.
  • phil294
    phil294 about 8 years
    @MarcusEkwall but wasn't the question asking for html rendering?
  • axlotl
    axlotl over 7 years
    I keep getting down-voted for this so here's a pen: codepen.io/axlotl/pen/YGZOEq
  • jeffrey crowder
    jeffrey crowder over 7 years
    This doesn't work in some browsers just adding this as a note AS of '16
  • Yash Sharma
    Yash Sharma almost 7 years
    can a placeholder be added inside this ?
  • Usman Ahmed
    Usman Ahmed over 6 years
    It does not use textarea. It uses div, which cannot be submitted with a form.
  • Fenil Shah
    Fenil Shah over 6 years
    It does work with textarea, just try giving id to textarea instead of div. I created a whole project using textarea and summernote. It works fine!
  • Usman Ahmed
    Usman Ahmed over 6 years
    Whats the point? It behaves same as ckeditor if textarea is used. Can't render HTML tags as asked.
  • mekwall
    mekwall over 6 years
    @NDZIEPatrickJoel Please refrain from linking to w3schools. They're a business that makes money off of phony certificates. Also, they don't allow anyone to contribute or fix bad code. Use MDN instead: developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/‌​…
  • Patanjali
    Patanjali over 5 years
    @mekwall. Despite whatever errors may be in w3schools, what they have over all the theoretical sites is that you can easily experiment in there, using multiple browsers, to see what actually happens! MDN is good for the completeness of coverage.
  • Luca De Nardi
    Luca De Nardi over 5 years
    Why should I use a WYSIWYG editor? This is really not an answer, sorry.
  • ogostos
    ogostos over 3 years
    what about applying style to only part of text?
  • ogostos
    ogostos over 3 years
  • Rahul Gandhi
    Rahul Gandhi over 3 years
    It doesn't use textarea. Not an answer.
  • Martin Meeser
    Martin Meeser over 3 years
    this is WOW - just WOW -saving me tons of work!
  • Martin Meeser
    Martin Meeser over 3 years
    looks like it is deprecated - what a shame
  • Martin Meeser
    Martin Meeser over 3 years
    if you put &lt;i&gt; test &lt;i&gt; then will it be shown in italic? no! but that is what is meant by "render".
  • BluJ IT
    BluJ IT almost 3 years
    As opposed to using editablecontent, I just used [innerHTML] within my div to accomplish what I needed: <div [innerHTML]="selectedLevel.longDescription"></div>
  • Peter Mortensen
    Peter Mortensen about 2 years
    What is it supposed to do? What is the gist of it?
  • Avatar
    Avatar about 2 years
    Interesting approach! Never thought of SVG graphics coming in handy here. But breaks when you add a < into the text.
  • merlin
    merlin about 2 years
    @Avatar though I didn't show it in this example for simplicities sake, you could work on a custom text parser to work with this. This added with a drawn text cursor rather than the default web cursor would enable you to do custom text much more easily. For example you can currently paste <b>hello</b> to get bold text. Adding a custom text parser to it and the possibilities are endless. You could make every a character red for example. I can see if I can find a more flushed out version of this I made a while ago If you would like.
  • merlin
    merlin about 2 years
    @Avatar I managed to find it though I have no idea what it even does anymore (I think it makes Ascii art by drawing lines above characters). jsbin.com/lacobib/3/edit?html,css,js,output
  • Avatar
    Avatar about 2 years
    Thanks for the link. It is advanced, maybe I will try an implementation in the future.