Firebug’s console.log() often breaks Javascript for users without Firebug (or a Webkit based browser), and seeing how much we love chaining with jQuery, there are two simple things you can do to make logging in both better.
Firebug: Wrap your logging
You can improve (and shorten!) your logging by implementing your own log() function, which checks whether console.log() exists in the browser before passing it’s arguments on.
function log() {
if (window.console && window.console.log) {
console.log.apply(this, arguments);
}
};
Just whack that bit of code into your Javascript, and use log() instead of console.log(). Broken JS no more.
jQuery: Make logging chainable
If you use the jQuery Javascript Library, you can extend jQuery and add a chainable log() method, so we can unobtrusively add the .log() method to take a look at any jQuery objects in our existing code.
// instead of wrapping code in a log() function
log($('#someElement'));
// we can just add .log() to the end
$('#someElement').log();
// or at any point in-between other methods
$('#someElement').log().parent().log().next().log();
Here’s the code you’ll need to add before any .log() calls
jQuery.fn.log = function() {
if (window.console && window.console.log) {
if (arguments.length) {
console.log("%o args: %o", this, arguments);
} else {
console.log(this);
}
}
return this;
};
1 comment
Hello
Blog
Canada
Contact
Nice article, nice blog, I have twittered your blog, it is worthy doing this. Thank you.
by anonymous Thu, 17 Jun 2010