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)
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.
25 hours later
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.
5 weeks later
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”);
55 weeks later
whatever
198 weeks later