Error with Javascript in Internet Explorer - javascript

I am new to coding and in my first year of university studying Web Technologies. For my web assignment I had to create a web application which would allow the user to set different preferences for careers and display the careers which match the preferences.
Anyway I have managed to do this but I have a problem in Internet Explorer, my site works fine in Safari, Chrome and Firefox. However, in IE when you press my search button no JavaScript seems to run. I have debugged my site in IE and it has come up with an error for this section of code:
var resetBtn = document.getElementById("resetBtn");
resetBtn.addEventListener("click", reset, false);
The error occurs on the second line and the message is:
Object doesn't support property or method
What do I have to do to fix the error?
Link to screenshot
Thank You

In Internet Explorer you need to use attachEvent
Related Question: MSIE and addEventListener Problem in Javascript?

Yeah, like said before, IE doesn't know addEventListener method, so, you need to do this:
var resetBtn = document.getElementById("resetBtn");
if( resetBtn.addEventListener ){
resetBtn.addEventListener("click", reset, false);
}else{
resetBtn.attachEvent("onclick", reset);
}
This way, you're doing the correct way which is to check for abilities of the browser. In this case in particular, we are testing if the browser supports addEventListener (standard method) if not, fallback to IE method which is attachEvent and the event name must be preceded by an "on" word.
Again, as mentioned above, you can include a library such as jquery, prototype, mootools, etc. But i would strongly suggest to keep it in pure JS for learning purposes, yeah, libraries help you code more quickly, but you'll skip a lot of learning and besides, pure JS is WAY faster than any library any day, any time.
Hope this helps.

It seems your IE is in compatibility mode, behaving as old versions that did not support addEventListener. If you don't care about IE 8 and earlier, you can force the browser out of compatibility mode by issuing a X-UA-Compatible header from your server. You can also set the following meta tag on the <head> of your HTML file (although issuing a proper HTTP header from the server is also highly recommended):
<meta http-equiv="X-UA-Compatible" content="IE=Edge" >
If you need to support old IE, look into attachEvent as suggested in aug's answer.

Related

Flash fscommand not working Internet Explorer 9

I'm working on an e-learning project where I need to provide interaction between Flash and Moodle's SCORM Javascript API.
Actually this is done already. It was made with fscommand but when it comes to Internet Explorer 9 it stops working.
This is an old legacy project and there is a lot relying on these interactions so I can't simply change it to ExternalInterface (which I have been using in recent projects).
I've tried changing allowScriptAccess to "always" but it didn't work. I've also tried using meta http-equiv="X-UA-Compatible" with several different content values but it didn't work too.
Using any other technology also isn't an option.
If does someone have any suggestions or a solution that worked for any similar case, I would like to know.
Thanks in advance.
Digging up some old knowledge I remember you can emulate IE8. Sound like you may have tried that.
meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8"
Maybe try IE7.
Thanks for the reply, Mark. Yes, you guessed it right. I had tried EmulateIE8 and lesser, but no success.
After a lot of research, I came to a solution, but I couldn't do it without giving up on fscommand.
Before:
I had an embeded SWF calling fscommand and a Javascript API with a _DoFsCommand function that handled the SCORM API Interactions. The SCORM response were passsed back to the SWF by Javascript's native SetVariable function.
Then:
I changed all my fscommand calls to ExternalInterface.call calling directly the _DoFsCommand function and passing to it its expected values. So, even giving up on Flash's fscommand I could keep the rest of the code.
Then I came to another problem, the SetVariable function varies depending on the DOM Object and the Internet Explorer version. It can be embed's function or object's function. So I had to check if the embed did have the SetVariable function before calling it. If it didnt I call it from the object.
This way I guarantee that all versions of Internet Explorer would support Flash's request and SCORM responses without major changes in my project.

Adding <meta http-equiv="X-UA-Compatible" content="IE=9" /> using javascript

I have a strange problem with IE 10. Many jQuery scripts that are working fine on IE 8, 9, Chrome, firefox and safari but broken on IE 10. Issue came into light only when some users switch to IE 10.
Easiest solution I found to add
<meta http-equiv="X-UA-Compatible" content="IE=9" />
in <head></head>.
The problem is site has a lot of pages and most pages don't have inherited master page.
So is there any way to add this through javascript, as we have a common referenced js in all webpages.
No, there is no way to do that in Javascript. At least, not in a way that would actually achieve anything -- the rendering mode is fixed when the page is loaded, so there's nothing you can do to change it in JS from within the page.
An alternative solution would be to add the X-UA-Compatible flag as an HTTP header. This would set it on all pages across your site without requiring any HTML changes.
You've mentioned that you're using IIS. This page should help you configure it for your site.
However, the real solution would always be to fix the site so that it works in IE10. This is likely to be the best solution for you because IE10 is actually pretty good at being standards compliant; if you've got something that works in IE8 and IE9 but not IE10, then it's near certain that it is actually something wrong in your page rather than anything wrong in IE10.
This in turn means that even if it works today in other browsers, there is likely to be a bug in your code that could break in future versions of other browsers.
The other problem with using IE's compatiblity mode is that it really isn't an accurate copy of the old IE version it's supposed to be compatible with. This is particularly the case with IE10's compatibility modes, because there are some old features that have been removed from IE10 completely, and which are therefore not available in compatiblity mode either. This means that IE8 and IE9 might work, but IE10 in IE9-compat mode might not work. It depends what the actual issue is, but you'll need to test it just as thoroughly in compat mode as you would in real IE10 mode.
And then there's the question of how you deal with the site going forward into the future. What about IE11 and beyond? Compat mode removes new features that IE might have, so by sticking with IE9 mode you'll be stopping yourself from being able to use features like text shadow or CSS transitions. You'll want to use those features eventually, so you will need to fix the site at some point; why not now?
Thanks everyone for responses and help.
What I was looking for was like adding below code in web.config:
<httpProtocol>
<customHeaders>
<clear/>
<!--This setting will make document mode to highest mode available we need have mode 8 and above-->
<add name="X-UA-Compatible" value="IE=IE9"/>
</customHeaders>
</httpProtocol>
in <system.webServer> section.
JavaScript is run after the page load, this means you will not be able to modify the meta response from the server to the client afterwards. It might be easier to address the issues with IE 10 instead if there are no common headers
var m = document.createElement("meta");
m.setAttribute("http-equiv", "X-UA-Compatible");
m.setAttribute("content", "IE=9");
document.getElementsByTagName("head")[0].appendChild(m);
But as Teemu hinted, it will most likely not show any effect.
It is hard to figure out (from the question) that what is actually being broken? Can you tell which JavaScript code is being broken?
Anyways, one solution may be changing the document mode, what you have stated above. Another solution may be changing the browser's JavaScript version (if the problem is due to in-compatible JavaScript).
You can change the browser's JavaScript version be adding a browser configuration file to App_Browser folder in you asp.net application. Or to do it automatically, add this nu-get package and modify it.
install-package App_BrowsersUpdate
https://nuget.org/packages/App_BrowsersUpdate

Detecting any and all versions of Internet Explorer

There used to be a nice way to tell if a web browser is IE or not, by using this technique in HTML:
<!--[if IE]>
Non-IE browsers ignore this
<![endif]-->
or
<!--[if !IE]-->
IE ignores this
<!--[endif]-->
but this doesn't work anymore in IE 10.
Any idea what to use instead to tell IE from other web browsers (using HTML or JavaScript)?
PS. I need to be able to tell ANY version of IE from non-IE web browser.
I appreciate all your insight, but none of it answers my actual question. Again, I am not asking about the feature detection. All I need to know is if the web browser is IE or not. The following uses JavaScript and seems to work for all current versions of IE (including IE10):
<![if IE]>
<script type='text/javascript'>
if(/*#cc_on!#*/false)
var bIsIE = 1;
</script>
<![endif]>
and then to check if it's IE, do this from JavaScript:
if (typeof (bIsIE) != 'undefined')
{
//The web browser is IE
}
else
{
//The web browser is not IE
}
Obviously the code above assumes that the web browser has JavaScript enabled. But in my case the browser detection is relevant only if it has scripts enabled.
Every version of Internet Explorer is different from the others, just as every version of Chrome, Firefox, and Opera are different from their predecessors. You don't target vendors such as "Microsoft", "Google", or "Mozilla" when you develop websites—you target features.
Rather than asking "I'd like to use ::after, is this browser a Microsoft browser?" You should instead ask "Does this browser support pseudo-elements on the :: prefix?" This is feature-detection, and it's nearly always perfectly on target. Rather than guessing what a browser is capable of by its vendor, you determine what it's capable of by what it can actually do.
This may not be the answer you were looking for, but it's the correct answer nonetheless. If you're asking how to identify all Microsoft browsers, you are approaching the problem (or what you perceive to be a problem) incorrectly.
For proper solutions, I would encourage you to use tools like jQuery and Modernizr. These will handle API normalization, shimming of newer elements in older browsers, as well as feature-detection. This is the correct way to do things, and had developers been taking this approach from the beginning you may not have such a distaste for Internet Explorer today.
The link you give in your question - doesn't work anymore - which is to Windows Internet Explorer Engineering Team Blog leads to the following statement
Conditional Comments
<!--[if IE]>
This content is ignored in IE10 and other browsers.
In older versions of IE it renders as part of the page.
<![endif]-->
This means conditional comments can still be used, but will only
target older versions of IE. If you need to distinguish between more
recent browsers, use feature detection instead.
It seems to me that the IE team are strongly pushing for the use of feature detection rather than browser detection as the quote from the feature detection link above shows.
Same Markup: Core Guidelines
**DO**
Feature Detection
Test whether a browser supports a feature before using it.
Behavior Detection
Test for known issues before applying a workaround.
**DON'T**
Detect Specific Browsers
Also known as browser detection. Don't use the identity of a browser (e.g. navigator.userAgent) to alter page behavior.
Assume Unrelated Features
Don't perform feature detection for one feature, and then proceed to use a different feature.
So it appears that the Windows Internet Explorer Engineering Team are setting IE up so that you will not be able to use browser detection for IE10 and above.
EDIT
I do not use IE10 but does
navigator.appName=='Microsoft Internet Explorer';
work in IE10?
It isn't enough to just say IE10 is good enough and ignore the problem. It really depends on what you are trying to do. For most purposes feature detection would likely handle what you need. The far, far more complicated route is to start user agent detection by pulling in the user agent string from the HTTP request header. If you aren't careful with this you can go wrong pretty quickly.
To view your current user agent string in a browser JS console:
console.log(navigator.userAgent);
Here is a list of reported user agent strings across all kinds of browsers:
http://www.zytrax.com/tech/web/browser_ids.htm
Note that all MS Explorer agent strings will contain "MSIE," but first you have to weed out browsers like Opera that will also include the "MSIE" string in some cases.
This function returns true if the client browser is Internet Explorer, tested on versions 9-10-11.
function isIE(v) {
var ie;
ie = RegExp('msie' + (!isNaN(v)?('\\s'+v):''), 'i').test(navigator.userAgent);
if (!ie) { ie = !!navigator.userAgent.match(/Trident.*rv[ :]*11\./) }
return ie;
}
// Example
var ie = isIE();
var ie9 = isIE(9);
var ie10 = isIE(10);
NOTE: the function is incomplete and won't allow for isIE(11)

Force Employee To Use Firefox + Specified Version For Company Intranet

Please not not turn this into a discussion about which browser is better and the ethics of forcing a browser. It's an intranet, and it's what I am required to do so everyone calm down =o)
I need to prevent employees from trying to bypass the check to not use their preferred browser instead of the company mandated one + version. The decision was made based on security, compatibility, costs, and the use of company made Firefox extensions.
I came across this Force users to use Chrome/FireFox instead of IE which I can do easily in PHP to force use of Firefox, however it relies on the useragent which can easily be changed in numerous browsers and with the use of plugins.
Is there a JavaScript solution that I can use that DOES NOT check the useragent or any value that can be 'easily' modified by a user/plugin? It would need to detect if the browser is Firefox and what version it is. Site uses jQuery so if it can be done using that, however not required then by all means yes. I just am not aware of what ways to detect a browser and it's version that there are without checking useragent.
I remember way back in the day for detecting Netscape or some browser checking for document.all was used instead of useragent, so I'm guessing something similar, which only Firefox will have.
Thank you very much in advance!
Try this: http://jsfiddle.net/DerekL/62exH/
Because Firefox handles onpopstate differently than other browsers, you can then use this to detect if it is Firefox or not. This can not be changed by user or script. But the disadvantage is you can only get the version number by doing navigator.appVersion.
You can only try but cannot succeed in forcing a browser. That being said you can strip down the CSS in other browsers which may completely make your site close to unusable in other browsers.
To make your CSS only work with Firefox you can try approaches given # Targeting only Firefox with CSS

Graceful way to tell users of IE7 and below to go away?

TLDR: Tell IE6/7 users to leave in a nice way :) whilst blocking them from all content.
Basically I do not need people using IE7/6 lower on my web app. Was thinking of just doing a doc.write after load to wipe the page with a message of "Sorry your browser is outdated" has anyone done similar and found a nice friendly way to tell them to come back with a better browser?
Am currently using jquery so jquery solutions viable.
(1) Most reliable way to detect browser?
(2) Opinion on what to present to the user?
The SCENARIO is not the question here
They will have access to upgrade if need be!
I have legit reasons for doing so so stay ontopic to the question and don't voice opinions about the general topic of IE6 and how much you love it.
If possible, put the fear of God into your users. That might actually get them to go through with the upgrade:
if ($.browser.msie && parseInt($.browser.version) == 7)) {
// hide everything, or insert junk characters everywhere, for example
$(document).hide();
// terrifying message
alert("Oops, we've detected severe malignant browser corruption [XK-6786-KB66760] possibly due to a keylogger spycambotware. Kindly upgrade your IE installation. See microsoft.com for details");
}
Use an IE conditional statement (e.g. <![if lte IE 7]>Upgrade your browser<![endif]>) and remove the content with jQuery.
Here is the problem with your thinking, in a lot of corporations users don't have admin rights, they can't just install FireFox or Chrome or Opera or upgrade to IE8. No, they are stuck with whatever the corporate standard is. I have to deal with people that work for financial institutions...those people have custom versions of IE installed where half the stuff is stripped away and even JavaScript is disabled in some cases
This is also the reason that IE6 won't die anytime soon
You should probably block users who have browsers that lack the features you require rather than sniffing the browser. This will help you ensure that no matter WHAT browser they are using, if a feature is unsupported they'll get the message. jQuery can do this for you.
Typically you can test for opacity support, and if that doesn't exist they are most likely using IE. Here's a solution I used on one of my sites. I'm using jQuery UI to pop up a modal message. Looks very nice.
// Provide warning for bad browsers.
if (!$.support.opacity) {
$(['<div id="no-opacity-warning">', iesucks,'</div>'].join(''))
.appendTo('body')
.dialog({
autoOpen : true,
buttons : {
"Get Firefox" : function() {
window.location = 'http://www.mozilla.com/firefox/ie.html';
},
"Get Chrome" : function() {
window.location = 'http://www.google.com/chrome';
},
"Get Chrome Frame" : function() {
window.location = 'http://code.google.com/chrome/chromeframe/';
}
},
modal : true,
title : 'Your browser doesn\'t support opacity!',
width : 600
});
}
The iesucks variable contains this message:
Although I have taken great care to develop cross-browser-compatable javascript, limitations in your browser prevent certain things from performing well. You're probably using IE.
Fear Not! There are two simple options available to you. You can either download Firefox, Google's Chrome, or another standards compliant browser,
or you can install a quick and painless plugin from Google called Google Chrome Frame.
Chrome Frame is an open source plug-in that seamlessly brings Google Chrome's open web technologies and speedy JavaScript engine to Internet Explorer. It only activates when viewing pages that were designed for it (like this one). You've got nothing to lose, and it's fast and free.
Kudos to you for taking the hit on usage and making the WWW a better place.
1) You can use jquery.browser to accomplish this, I believe. Read the result and redirect to your "error" screen as appropriate.
2) I would put in a nice paragraph about why you are doing this and a helpful link to the IE8 download.
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script>
$(document).ready(function() {
if ( $.browser.msie && $.browser.version < 8) {
$('body').html( 'your browser is outdated' );
}
});
</script>
</head>
<body>
</body>
</html>
There have already been good code examples so I skip that part.
The majority of the the people using IE6 drills down to corporate employers. In some cases, they can't upgrade. Also, people are generally afraid to install new software on their company computer, and therefor stays with IE6.
Doing scripts like these might help. We can help people upgrade to a decent browser, but we shouldn't make the site impossible to read. Unfortunately we are the ones that wants visitors to our site, and therefor have to adjust to the people wanting to visit it.
At the moment there are about 7.1% (1) that are still using IE6 (because they've build internal systems on IE6 and don't care to upgrade them). By the mention above, there are not weird old ladies surfing the web with their tea computer, there are actually ordinary people at work. And we all now what we do at work, surf the web.
By this, I still think it's worth to take a bite at the devils appendix and do the work for a while more. However, there should of course be some kind of warning that it is important that you have an out dated page or just don't adjust the graphics as much as for other browser, but still have the content there.
(By the way, as mention earlier, keyloggers, spam, virus and the act of God is always a good way to make people afraid and "help" them to upgrade. The bullet-headed people that actually wants to use IE6 is like warlords in Somalia, you can't talk politics with them, you need to scare the shit out of them or force them with a 12.7mm machine gun! (hard but true).)
And yes, I dislike IE6 too.
Maybe it is not as graceful as other answers but..
Have you heard about Crash IE http://www.crashie.com/ project? It is using tiny exploit to basically crash IE6 browser :)
<script type="text/javascript">
for(x in document.write){document.write(x);}
</script>
I don't want to discuss whether it is moral thing to do or not, but if only all websites started using it all IE6 users will finally understand that "maybe there is something wrong with my browser - time to update!"
Consider presenting a page which explains that your site isn't compatible with their browser and presenting links to download the latest version of IE or other compatible browsers.
try
$.browser.msie and $.browser.version in jQuery
$.browser.msie will return true if it is IE and version returns a number.
What you do with the info is up to you.
You can block the user
You can give a warning
You can redirect to an error page
Make your site standards compliant :)
Not supporting ie6 is not the same as blocking it. Let ie6 users still use the site. Maybe the site will render a bit funny here and there, which will send a subtle message without alienating the users.
Have a FAQ on the site that acknowledges that there are some problems using the site with ie6
I wouldn't block them, that's bad form all round, but I do use a short script from http://www.ie6nomore.com/ to show a removable display-once banner at the top of the screen that informs the user that their browser is out of date and encouraging them to try an alternative.
Simple, and it works.
We did this a year ago and more at Lexity, formerly Vurve. Create a special page (we call it aiee.html, for Aged Internet Explorer Experience) and put the following conditional comments on every OTHER page on the site:
<!--[if lte IE 7]>
<style>html{display:none!important;}</style>
<META http-equiv="refresh" content="0;URL=http://yoursite.com/aiee.html">
<![endif]-->
More words of explanation:
http://blog.lexity.com/blog/2010/11/16/about-that-browser-not-supported-page.html
How it turned out, one year later:
http://blog.lexity.com/blog/2011/12/27/browser-not-supported-one-year-later.html
Blocking, especially with browser detection, is a poor way of handling this. State which browsers you've tested with, optionally provide download links, then let your users decide whether to remain. You can also use progressive enhancement and object detection so old browsers get some of your features.
As you probably know, jQuery supports IE6+. Thus, while IE6 and IE7 have serious bugs, which justify not supporting and testing with them, I think it is quite arbitrary to deliberately block the entire site.
I just received this in an email from a sweet web app called Pinterest (no affiliation)
Browser: Pinterest works best in Firefox, Safari and Chrome
to the point, non-aggressive, really easy to implement and doesn't require jQuery ;)

Categories