Edit HTML PRE Code with Textarea

Edit HTML PRE Code with Textarea

by Adi Jaya

HTML

<div class="section-code">
<h3>Double click for Edit code</h3>
<pre><code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;title&gt;HTML Tutorial&lt;/title&gt;
&lt;body&gt;

&lt;h1&gt;This is a heading&lt;/h1&gt;
&lt;p&gt;This is a paragraph.&lt;/p&gt;

&lt;/body&gt;
&lt;/html&gt;</code></pre>
</div>

<div class="section-code">
<h3>Double click for Edit code</h3>
<pre>body {
  background-color: lightblue;
}
h1 {
  color: white;
  text-align: center;
}
p {
  font-family: verdana;
  font-size: 20px;
}</pre>
</div>

CSS

* {
  box-sizing: border-box;
}

pre, .textarea-edit {
    padding: 15px;
    overflow: auto;
    font-size: 15px;
    border: 1px solid silver;
    display: block;
    font-family: monospace;
    white-space: pre;
    margin: 1em 0px 1em;
}
pre code {
  color:inherit;
  display: block;
}
.section-code textarea {
    outline-color: green;
    resize: none;
    width: 100%;
    background: #fffac8;
}
.section-code.active pre, .section-code.active code {
  display: none;
}

JavaScript

$(function() {
	
  //Double click
	$( document ).on( "dblclick", "pre", function(){
  		var parent = $( this ).parents( ".section-code" );
      var text   = $( this ).text();
      var height   = $( this ).outerHeight();
      if( parent ){
      		parent.append( "<textarea style='height:"+height+"px' spellcheck='false' class='textarea-edit'>"+text+"</textarea>" );
          parent.addClass( "active" );
      }
      //more function here
      
  });
  
  //Edit Code
  $( document ).on( "blur", ".textarea-edit", function(){
  		var parent = $( this ).parents( ".section-code" );
      var pre = parent.find( "pre" );
      var value = $( this ).val();
      
      if( pre.children('code').length > 0 ){
      	pre.children('code').empty().text( value );
      }
      else {
      	pre.empty().text( value );
      }
      parent.removeClass( "active" );
      $( this ).remove();
      //more function here
      
  });
  
  $( document ).on( "keyup", ".textarea-edit", function(){
  		var $this = $( this );
      var scroll_height = $this.get(0).scrollHeight;
      $this.css({
      	'height' : scroll_height + 'px',
        'overflow':'hidden'
      });
      //more function here
      
  });
  
});