jQuery & JavaScript in Internet Explorer 8: 'Object does not support this property or method' and 'console' is undefined [solution]
While using jQuery and JavaScript for developing web applications you could encounter some problems with Microsoft Internet Explorer 8 which doesn’t occur in other web browsers, or at least they don’t break your application like IE 8 does.
First of all lets tweak Internet Explorer to display notification about every script error, otherwise and error could occur and you wouldn’t even notice that.
‘Object does not support this property or method’ error
This error happens if you call event.preventDefault();
Imagine you have link in your HTML code
<a href="#" id="moreInfo">Show</a>
and you want to prevent default link behaviour after clicking on that link, so you use event.preventDefault(); which I’ve used on line 3 in code bellow:
1 $("#moreInfo").click(function(event) {
2 showHideDiv('#moreInfo', false);
3 event.preventDefault();
4 });
but in Internet Explorer 8 you get ‘Object does not support this property or method’ error.
You could fix it like this:
1 if(event.preventDefault) {
2 event.preventDefault();
3 }
4 else {
5 event.returnValue = false;
6 }
or even more elegant one line version while using ternary operator, which I’ve prefer:
1 event.preventDefault ? event.preventDefault() : event.returnValue = false;
‘console is undefined’ error
This is very dangerous error because it completely breaks JavaScript/jQuery on the whole page and without that error notification settings turned on you won’t even notice that.
This error occurs when you want to use JavaScript logging and you don’t check if window.console is defined.
So if you have in your JavaScript code like this:
console.log('Foo bar!');
you get an ‘console is undefined’ error.
You could fix this by adding following check:
if(window.console){ console.log('Loren ipsum'); }
And last note, if you use Developer Tools in Internet Explorer (shortcut F12) and error won’t happen so you might shake your head off while looking what’s broken in your code.
‘is undefined’ error
Lets imagine that you have two JavaScript files linked (it could be inlined JavaScript blocks also) to one HTML file. First is linked to Template/Theme and second one to content and in that second file you want to check if object is defined in that first file.
First block:
1 <script type="text/javascript">
2 window.ChatDef = window.ChatDef || {};
3 ChatDef.user = ChatDef.user || {};
4 ChatDef.user.firstName = 'John';
5 </script>
Second block:
1 <script type="text/javascript">
2 // Check if object ChatDef exists at code or file linked above this script
3 if(!(typeof ChatDef === "undefined")) {
4 // JavaScript operations with ChatDef goes here
5 }
6 </script>
So with check on line 3 in code above you won’t get ‘ChatDef is undefined’ error.