Last active
August 29, 2015 14:26
-
-
Save elrac/87deb9181e2c63a35bef to your computer and use it in GitHub Desktop.
A js script for printing console logs on the page as well as in the console.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function () { | |
// add a div with id='consoleLog' to the document and | |
// it will have the console log in it. If that div doesn't | |
// exist then this code does nothing. | |
var style = document.createElement('style'); | |
style.setAttribute("type", "text/css"); | |
style.textContent = ".info{background-color:lightGreen;}.warn{background-color:yellow}.error{background-color:lightPink}#consoleLog{border:medium double;}"; | |
document.querySelector('head').appendChild(style); | |
['log', 'info', 'warn', 'error'].forEach(function (verb) { | |
console[verb] = (function (method, verb) { | |
return function () { | |
var args = []; | |
for (var i = 0; i < arguments.length; i++) { | |
args.push(arguments[i]); | |
} | |
method.apply(console[verb], args); | |
var log = document.querySelector('#consoleLog'); | |
if (log) { | |
var text = args.reduce(function (previous, current) { | |
var txt = current; | |
if (typeof current === 'object') { | |
txt = JSON.stringify(current); | |
} | |
return previous + ' ' + txt; | |
}, ''); | |
var msg = document.createElement('code'); | |
msg.classList.add(verb); | |
msg.textContent = verb + ': ' + text; | |
log.appendChild(msg); | |
log.appendChild(document.createElement('br')); | |
} | |
}; | |
})(console[verb].bind(console), verb); | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment