0
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?

David Levesque
  • 22,181
  • 8
  • 67
  • 82
dwjohnston
  • 11,163
  • 32
  • 99
  • 194
  • what browser? also can you produce a [jsFiddle](http://jsfiddle.net/) that can reproduce it? – Mgetz Jan 21 '14 at 22:06
  • @Mgetz. Huh. If I use IE8 it displays all three (haven't worked out where it logs to yet). It doesn't display the third when running it in the eclipse browser. – dwjohnston Jan 21 '14 at 22:23

2 Answers2

2

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");
}
David Levesque
  • 22,181
  • 8
  • 67
  • 82
  • Why the downvote? This answer is correct, in Internet Explorer, `console` is not defined until the devtools have actually been opened. – Rob W Jan 21 '14 at 22:06
  • Thank you. I think I had a misunderstanding of what console.log was - I was thinking it was something like stdOut, but that's not really the case? For my purposes, just using IE8 instead of the eclipse browser works. This question here is relevant. http://stackoverflow.com/questions/4539253/what-is-console-log?rq=1 – dwjohnston Jan 21 '14 at 22:32
0

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;
    }
}
}());
SK.
  • 4,174
  • 4
  • 30
  • 48