Tonza Tonza - 4 months ago 11
HTML Question

Show html tags as a text

I'm making small html editor for my website.

enter image description here
My editor

<textarea class="editor"></textarea>


Example window

<div class="results"></div>


Javascript and JQuery

function textarea_post(){
var text = $(".editor").val();
text = text.replace(/<code>/g,"<pre>").replace(/<\/code>/g,"</pre>");
$(".results").html(text);
}

$(".editor").on("keydown keyup paste",function(e){
textarea_post();
});


My code replace
<code></code>
tags from editor with
<pre></pre>
tags.

The problem is that you can't do html code snippet between
<pre></pre>
.

Html code needs to be shown as a text not as html itself between
<pre></pre>
.

Outside
<pre></pre>
other tags needs to be shown as a html

Answer

I think most of what you are you are trying to do can be accomplished through css; your javascript seems to be fine; but your html needs slight adjustment as center tags are deprecated and not supported in html.

Have a look at this snippet or fiddle (just press enter at the end of the textarea)

EDIT: updated to include better script from Mohit, but note the center tags!

function textarea_post() {
   var text = $(".editor").val();
    text = text.replace(/<code>/g,"<pre>").replace(/<\/code>/g,"</pre>");
    $(".results").html(text);
    $(".results pre").each(function(){
      var escapedText = $(this).html();
      $(this).text( escapedText );
    });
}

$(".editor").on("keydown keyup paste", function(e) {
 if (e.which==13){
  textarea_post();
  }
});
textarea, .editor {
  width: 80vw;
  height: 150px;
  overflow-y:scroll;
}

h2 {
  text-align: center;
  background-color:white;
  color:darkblue;
  margin-top:0;
  border-bottom:1px #000 dashed;
}
.results{background-color:lightgrey;
width:80vw;
border:1px solid;
overflow-y:scroll;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="editor">
  <h2>Example 1</h2>
  <code>
    function MyFunction(a, b){
     return a+b;
    }
    MyFunction(5, 10)
    <h1>hello</h1>
  </code>


</textarea>

<div class="results"></div>

Hope this helps - post a comment if this is not the desired effect/if i have misunderstood.