Skip to content

Instantly share code, notes, and snippets.

@benaubin
Last active March 28, 2016 02:10
Show Gist options
  • Save benaubin/2d5c176b2ca72e67912e to your computer and use it in GitHub Desktop.
Save benaubin/2d5c176b2ca72e67912e to your computer and use it in GitHub Desktop.
A nice way of making javascript in `<code>` blocks editable.
function addScript(src,callback){
var s = document.createElement('script');
s.setAttribute('src', src);
s.onload = callback;
document.body.appendChild(s);
}
function addStyles(){
var s = document.createElement('style');
s.innerText = "\
span.result.error {\
display: block;\
color: red;\
}\
.code {\
min-width: 10px;\
}"
document.head.appendChild(s);
}
addStyles()
addScript("https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js", function(){
var code = $('span.code');
$('span.code').after('<br>')
code.attr('contenteditable', 'true').each(function(i, e) {
$("<span></span>").text(" //=>").addClass('result').insertAfter(e);
});
interactive($('span.code'));
function interactive(code){
code.keydown(function(e){
if((e.keyCode || e.which) == 13){
var _this = $(this);
_this.clone().html("").insertAfter(_this.next().next())
.show().focus().after(
template.clone().removeClass('result-template').show()
).next().after('<br>')
interactive();
e.preventDefault();
}
}).keyup(function(e) {
var error = false,
context = {}
if((e.keyCode || e.which) != 13){
$('span.code').each(function() {
var _this = $(this),
res = _this.next().show().removeClass('error');
try {
with(context) {
res.html(error ? "" : " //=> " + eval(_this.text()))
}
} catch (e) {
error = e;
res.html(" Error: " + error.message).addClass('error');
}
})
}
})
}
$.fn.reduce = [].reduce;
})

#Code Sample This is for making some code editable and usable - and it shows the output - pretty neat :D

#Usage:

  1. Put this in your HTML:
<script src="https://gist.github.com/penne12/2d5c176b2ca72e67912e/raw/codesample.js"></script>
  1. Put code blocks in your HTML.
  2. Profit.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment