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><!DOCTYPE html>
<html>
<title>HTML Tutorial</title>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html></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
});
});