dwjohnston
dwjohnston

Reputation: 11771

console.log causes code to stop running

document.getElementById('myButton').onclick = function()
{    
    alert("button click");
    alert("bclick2");
    console.log("console log");
    alert("bclick3");
};

When I run this in eclipse on a tomcat server, the first two dialog boxes will display, but not the third, which makes me think that it's the console.log command that isn't working.

What is likely to be the problem?

Upvotes: 0

Views: 632

Answers (2)

SK.
SK.

Reputation: 4358

For a more robust solution, use this piece of code (taken from twitter's source code):

// Avoid `console` errors in browsers that lack a console.
(function() {
var method;
var noop = function () {};
var methods = [
    'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
    'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
    'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
    'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});

while (length--) {
    method = methods[length];

    // Only stub undefined methods.
    if (!console[method]) {
        console[method] = noop;
    }
}
}());

Upvotes: 0

David Levesque
David Levesque

Reputation: 22441

You are most likely getting a javascript error that prevents the remaining code to run. The console object is only available when debug tools (like Firebug) are present. To avoid javascript errors when it is not available, you can surround it by a check like this:

if (window.console && window.console.log) {
    console.log("console log");
}

Upvotes: 2

Related Questions