Tuesday, July 22, 2008

How About a Quick Debug Output Window

One of the first things most Javascript developers learn is how to display an alert box. As they progress in their Javascript skills, they very soon realize that it's a bit of a black box and start to use those alerts to debug their code. Javascript has progressed over time and nowadays there are pretty decent debuggers. But often times you just need a console window to write output to. I wanted to write a very small little piece of code that allowed me to write debug output. This piece of code would allow me to simply paste it into the current Javascript I'm debugging and with one command, allow me to write to the debug window. I wanted to use Object Literal Syntax (AKA JSON) as well so I don't have to instantiate an instance of it. Well, with just a few lines of code, I was able to do that and I wanted to share it with you. It's not rocket science and would be fun to modify to see how much bang for your buck you could get out of it. Let me know what you think and even throw some suggestions out or add some code. Just paste this code somewhere into the Javascript code your are using:


var DBG = {
write : function(txt){
if (!window.dbgwnd){
window.dbgwnd = window.open("","debug","status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=0,scrollbars=1,width=600,height=250");
window.dbgwnd.document.write('<html><head></head><body style="background-color:black"><div id="main" style="color:green;font-size:12px;font-family:Courier New;"></div></body></html>');
}
var x = window.dbgwnd.document.getElementById("main");
this.line=(this.line==null)?1:this.line+=1;
txt=this.line+': '+txt;
if (x.innerHTML == ""){
x.innerHTML = txt;
}
else {
x.innerHTML = txt + "<br/>" + x.innerHTML;
}
}

To write to the console, just add this line:

DBG.write("This is console output!!");

Enjoy!!

8 comments:

Anonymous said...

This is pretty cool. I like the fact that it is a separate window. One note, you are missing the last closing }. I also added an init fuction so that I could open the debug window as soon as my page loaded instead of waiting for the first debug statement.

Mike Maddox said...

Great idea about the init function. Thanks.

Anonymous said...

Mike, how did you get the gray box around your code? I have made some significent improvements and want to attach them.

Mike Maddox said...

Cool. Looking forward to it. I just added a DIV around the code with background set to gray. Anther option is to add a <code> tag which will make it Orange with my template. Thanks for the update.

Anonymous said...

Great code, simple and extremely useful. THANKS.

Anonymous said...

Great code, simple and extremely useful. THANKS.

Unknown said...

Man, this is great !!

Daniel Latikaynen said...

excellent!
escpecially since some of us are still forced to use IE, and there, Firebug's console extension is not (currently) supported