Quick JavaScript debugging tip

If you’re doing a lot of JavaScript debugging, you tend to put alert() statements all over the place (well, I do, anyway). They can interrupt things somewhat. Instead, stick this in an included JS file somewhere:

alert = function(s) {
  var ta = document.getElementById('debug');
  if (!ta) {
    var ta = document.createElement('textarea');
    ta.id = 'debug';
    ta.rows = 8; ta.cols = 80;
    document.body.appendChild(ta);
  }
  ta.value += s+'\n';
}

Then, whenever you do alert('whatever');, it’ll just add to a textarea that it creates in your page. You can scroll back through the errors, and you can put alerts inside a loop without fearing that you’ll have to click “OK” fifty times next time you test the page.
(Update: doesn’t work in Internet Explorer)

4 Responses to “Quick JavaScript debugging tip”

  1. A very cool idea – shame you can’t override the alert function in IE :-(

    You could of course call your debug function something else, debug(s) for example – which would help to identify your debug code too. That would avoid overwriting the default behaviour of the useful alert box too.

    Richard@Home
  2. another (similar) idea: construct a function which uses the innerHTML method to write as much as you want to some predesignated area of the page.

    rj
  3. To respond to Richard’s post
    “shame you can’t override the alert function in IE :-( ”
    Well Richard you can and below is how you would do that.

    window.alert = new Function (”myAlert()”);

    myAlert = function(s) {
    var ta = document.getElementById(’debug’);
    if (!ta) {
    var ta = document.createElement(’textarea’);
    ta.id = ‘debug’;
    ta.rows = 8; ta.cols = 80;
    document.body.appendChild(ta);
    }
    ta.value += s+’\n’;
    }
    window.alert = myAlert;

    alert(”sdf”);

    Brian Caudill
  4. whatever

    Anonymous

Leave a Reply

OpenID is a decentralised authentication system. If you use LiveJournal or Vox you already have an OpenID; just use the URL of your homepage there. See also how to get yourself an OpenID.