title: How to make a live HTML preview textarea safe against HTML/Script Injection
body: <p>I'm turning here as a last resort. I've scoured google and I'm having troubles coming to a solution. I have a form with a textarea element that allows you to type html in the area and it will render the HTML markup live as you type if you have the preview mode active. Not too different from the way StackOverflow shows the preview below a new post.</p>
  
  <p>However, I have recently discovered that my functionality has a vulnerability. All I got to do is type something like:</p>
  
  <pre><code>&lt;/textarea&gt;
       &lt;script&gt;alert("Hello World!");&lt;/script&gt;
  &lt;textarea style="display: none;"&gt; 
  </code></pre>
  
  <p>And not only does this run from within the textarea live, if you save the form and reload said data on a different page this code still executes within the textarea on said different page but unbeknownst to the user; to them all the see is a textarea (if there is no alert obviously).</p>
  
  <p>I found this post; <a href="https://stackoverflow.com/questions/12270749/live-preview-of-textarea-input-with-javascript-html">Live preview of textarea input with javascript html</a>, and attempted to refactor my JS to the accepted answer there, because I noticed I couldn't write a script tag in the JSFiddle example, though maybe that's some JSFiddle blocking that behaviour, but I couldn't get it working within my JS file.</p>
  
  <p>These few lines is what I use to live render HTML markup:</p>
  
  <pre><code>$(".main").on("keyup", "#actualTextArea", function () {
      $('#previewTextArea').html($('#actualTextArea').val());
  });
  
  $(".main").on("keydown", "#actualTextArea", function () {
      $('#previewTextArea').html($('#actualTextArea').val());
  });
  </code></pre>
  
  <p>Is there a way this can be refactored so it's safe? My only idea at the moment is to wipe the live preview and use a toggle on/off and encode it, but I really think this is a cool feature and would like to keep it live instead of toggle. Is there a way to "live encode" it or escape certain tags or something?</p>