Debugging in javascript without alert dialog

To debug javascript code we use alert() whereever needed and it irritates you while alerts values inside a loop and other places where more alerts are being shown and you have to press the ok button to pass / proceed on.
here is a simple way to get rid of the alerts dialogs and get the values outputed into another debug window



var dwin = null;
function debug(msg) {
if ((dwin == null) || (dwin.closed)) {
dwin = window.open("","debugconsole","scrollbars=yes,resizable=yes,height=100,width=300");
dwin.document.open("text/html", "replace");
}
dwin.document.writeln('
'+msg);
dwin.scrollTo(0,10000);
dwin.focus();
// dwin.document.close();  // uncomment this if you want to see only last message , not all the previous messages
}

add the above code in you page first. Try the following for example. for(var i=0;i<10;i++){ debug(i); //… you other statements here } this will open a new debug window and show/ouputs the value of i

6 Replies to “Debugging in javascript without alert dialog”

  1. I struggled a long time with that question, my final tough was to write something similar, but Firebug 1.0 beta came out and saved the day.

    Really, take my word, those next line will change your debugging life forever;

    // If firebug isn’t present just do nothing.
    if(typeof console != ‘object’) {
    console = {};
    console.log = function(){return false;};
    }
    window.onload = function() {
    console.log(‘The windows has been loaded !’, window);
    }

    And guess what ? because “window” has been passed as second parameter and is an object, it will be displayed as a clickable link which allow you to browse the window object and change propreties .. live 🙂

    And it’s only one of the many cool features of firebug, really you need nothing else.

    Cheers

Leave a Reply to Binny V A Cancel reply

Your email address will not be published. Required fields are marked *