Javascript: change based on whether IE7 or not - javascript

I would like to change a line of my javascript code based on whether the browser is IE7 or not. Here is the code for any other browser:
function showHint(myId)
{
document.getElementById(myId).style.display = "inline-block";
}
For IE7, I want display = "inline".
I've made an attempt at conditional compilation (this showed me how to detect the browser), but it didn't work:
function showHint(myId)
{
document.getElementById(myId).style.display = "inline-block";
/*#cc_on
#if(navigator.appVersion.indexOf(“MSIE 7.”)!=-1)
{
document.getElementById(myId).style.display = "inline";
}
#*/
}
Any help is greatly appreciated!
EDIT: I'm not using JQuery.

Set a global determined by the behavior of IE's conditional comment parsing:
<!--[if IE 7]><script> var isIE7 = true; </script><![endif]-->

You need to check navigator.userAgent.
If you use jQuery, you can simply write
if ($.browser.msie && $.browser.version === 7)

I think you can use regular expression to determine MSIE 7:
if(/MSIE 7/.test(navigator.appVersion)) { /* msie7 related code */ }

There is a Jquery Plugin detecting the Browser Version. I do not know the exact Link ...

Conditional compilation should work. It seems that your error is that you are using fancy quotes to delimit a string (“MSIE 7.”) or that you are attempting to assign display to something unknown to IE and it is having a fit over it and throwing an error. Here is a more concise version of the function that doesn't repeat itself and solves this issue:
function showHint(myId)
{
document.getElementById(myId).style.display = "inline" //#cc_on;
+ "-block";
}

Related

Jquery issues on older versions of IE

I have the following statement in document.ready function:
if($("sidebar ").html().trim().length == 0)
{
$("sidebar").append("<p> The sides..</p>");
};
It works fine in IE 9 but as soon as I select IE 8 (browser and document standard), the script stops working and gives the following error:
SCRIPT5007: Unable to get value of the property 'trim': object is null or undefined
application-e51c9eee7d22e9644481115dc1fedd5f.js, line 7 character 17578
I looked at the .js in debug mode and see that my statement above is transformed to:
$("sidebar ").html().trim().length==0&&$("sidebar").append("<p> The sides..</p>")
How do I prevent this error? Please note that I do see that the node is present in the rendered page.
I thought that maybe just having reference to shiv5.html may not be sufficient to take care of the IE idiosyncrasies. So, I have added modernizr.js via sprockets and I have added class="no-js" in my layout. Still no luck in IE <9.
What am I missing? What else can I do to get the favor of Microsoft overlords?
According to MDN, trim isn't available in IE < 9.
You could use $.trim instead:
if($.trim($("sidebar ").html()).length == 0)
{
$("sidebar").append("<p> The sides..</p>");
} // <-- Don't want a semicolon here.
The MDN article lists an alternative if you don't want to find all the instances of trim and correct them. You could use the following to create .trim if it's not natively available:
if(!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g,'');
};
}
Check out this thread. After a quick search it seems that many people are experiencing issues with trim.

Best way to check for IE less than 9 in JavaScript without library

What would be your fastest, shortest (best) way to detect browser which is IE and version less than 9 in JavaScript, without using jQuery or any add-on libraries?
Javascript
var ie = (function(){
var undef,
v = 3,
div = document.createElement('div'),
all = div.getElementsByTagName('i');
while (
div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
all[0]
);
return v > 4 ? v : undef;
}());
You can then do:
ie < 9
By James Panolsey from here: http://james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments
for what it's worth:
if( document.addEventListener ){
alert("you got IE9 or greater");
}
This successfully targets IE 9+ because the addEventListener method was supported very early on for every major browser but IE. (Chrome, Firefox, Opera, and Safari) MDN Reference. It is supported currently in IE9 and we can expect it to continue to be supported here on out.
Using conditional comments, you can create a script block that will only get executed in IE less than 9.
<!--[if lt IE 9 ]>
<script>
var is_ie_lt9 = true;
</script>
<![endif]-->
Of course, you could precede this block with a universal block that declares var is_ie_lt9=false, which this would override for IE less than 9. (In that case, you'd want to remove the var declaration, as it would be repetitive).
EDIT: Here's a version that doesn't rely on in-line script blocks (can be run from an external file), but doesn't use user agent sniffing:
Via #cowboy:
with(document.createElement("b")){id=4;while(innerHTML="<!--[if gt IE "+ ++id+"]>1<![endif]-->",innerHTML>0);var ie=id>5?+id:0}
bah to conditional comments! Conditional code all the way!!! (silly IE)
<script type="text/javascript">
/*#cc_on
var IE_LT_9 = (#_jscript_version < 9);
#*/
</script>
Seriously though, just throwing this out there in case it suits you better... they're the same thing, this can just be in a .js file instead of inline HTML
Note: it is entirely coincidental that the jscript_version check is "9" here. Setting it to 8, 7, etc will NOT check "is IE8", you'd need to lookup the jscript versions for those browsers.
Below is an improvement over James Padolsey's solution:
1) It doesn't pollute memory (James' snippet creates 7 unremoved document fragments when detecting IE11, for example).
2) It's faster since it checks for a documentMode value before generating markup.
3) It's far more legible, especially to beginning JavaScript programmers.
Gist link: https://gist.github.com/julianshapiro/9098609
/*
- Behavior: For IE8+, we detect the documentMode value provided by Microsoft.
- Behavior: For <IE8, we inject conditional comments until we detect a match.
- Results: In IE, the version is returned. In other browsers, false is returned.
- Tip: To check for a range of IE versions, use if (!IE || IE < MAX_VERSION)...
*/
var IE = (function() {
if (document.documentMode) {
return document.documentMode;
} else {
for (var i = 7; i > 0; i--) {
var div = document.createElement("div");
div.innerHTML = "<!--[if IE " + i + "]><span></span><![endif]-->";
if (div.getElementsByTagName("span").length) {
return i;
}
}
}
return undefined;
})();
var ie = !-[1,]; // true if IE less than 9
This hack is supported in ie5,6,7,8. It is fixed in ie9+ (so it suits demands of this question). This hack works in all IE compatibility modes.
How it works: ie engine treat array with empty element (like this [,1]) as array with two elements, instead other browsers think that there is only one element. So when we convert this array to number with + operator we do something like that: (',1' in ie / '1' in others)*1 and we get NaN in ie and 1 in others. Than we transform it to boolean and reverse value with !. Simple. By the way we can use shorter version without ! sign, but value will be reversed.
This is the shortest hack by now. And I am the author ;)
I've decided to go with object detection instead.
After reading this:
http://www.quirksmode.org/js/support.html
and this:
http://diveintohtml5.ep.io/detect.html#canvas
I'd use something like
if(!!document.createElement('canvas').getContext) alert('what is needed, supported');
This link contains relevant information on detecting versions of Internet Explorer:
http://tanalin.com/en/articles/ie-version-js/
Example:
if (document.all && !document.addEventListener) {
alert('IE8 or older.');
}
You could do it in a quick and dirty fashion with a regular expression and .match():
if (navigator.userAgent.match(/MSIE\s(?!9.0)/)) {
// ie less than version 9
}
If I were you I would use conditional compilation or feature detection.
Here's another alternative:
<!--[if lt IE 9]><!-->
<script>
var LTEIE8 = true;
</script>
<!--<![endif]-->
I liked Mike Lewis' answer but the code did not pass jslint and I could not understand the funky while loop. My use case is to put up a browser not supported message if less than or equal to IE8.
Here is a jslint free version based on Mike Lewis':
/*jslint browser: true */
/*global jQuery */
(function () {
"use strict";
var browserNotSupported = (function () {
var div = document.createElement('DIV');
// http://msdn.microsoft.com/en-us/library/ms537512(v=vs.85).aspx
div.innerHTML = '<!--[if lte IE 8]><I></I><![endif]-->';
return div.getElementsByTagName('I').length > 0;
}());
if (browserNotSupported) {
jQuery("html").addClass("browserNotSupported").data("browserNotSupported", browserNotSupported);
}
}());
Does it need to be done in JavaScript?
If not then you can use the IE-specific conditional comment syntax:
<!--[if lt IE 9]><h1>Using IE 8 or lower</h1><![endif]-->
if (+(/MSIE\s(\d+)/.exec(navigator.userAgent)||0)[1] < 9) {
// IE8 or less
}
extract IE version with: /MSIE\s(\d+)/.exec(navigator.userAgent)
if it's non-IE browser this will return null so in that case ||0 will switch that null to 0
[1] will get major version of IE or undefined if it was not an IE browser
leading + will convert it into a number, undefined will be converted to NaN
comparing NaN with a number will always return false
You are all trying to overcomplicate such simple things. Just use a plain and simple JScript conditional comment. It is the fastest because it adds zero code to non-IE browsers for the detection, and it has compatibility dating back to versions of IE before HTML conditional comments were supported. In short,
var IE_version=(-1/*#cc_on,#_jscript_version#*/);
Beware of minifiers: most (if not all) will mistake the special conditional comment for a regular comment, and remove it
Basically, then above code sets the value of IE_version to the version of IE you are using, or -1 f you are not using IE. A live demonstration:
var IE_version=(-1/*#cc_on,#_jscript_version#*/);
if (IE_version!==-1){
document.write("<h1>You are using Internet Explorer " + IE_version + "</h1>");
} else {
document.write("<h1>You are not using a version of Internet Explorer less than 11</h1>");
}

Can you test for browser support for -moz-linear-gradient?

I would like to use feature detection to tell whether the user's version of Firefox supports the CSS style value -moz-linear-gradient. (This was added in Gecko 1.9.2. Version 3.6 of Firefox uses this.)
I can't use document.body.style.mozLinearGradient (or something similar) because -moz-linear-gradient is not a style property but a style value.
Does anyone know how to test for this without using version numbers?
I'm not sure how, but Modernizr (a nice little feature-detection script) appears to do it.
I guess you could create an (offscreen?) element, set that as it's style, and then poke around in the DOM to see if the browser successfully applied it?
Just assign it as style value and check afterwards if it is there.
Kickoff example:
function supportsMozLinearGradient() {
var element = document.getElementsByTagName('script')[0]; // Just grab an "invisible" element.
var oldstyle = element.style.background; // Backup old style.
try {
element.style.background = '-moz-linear-gradient(top, black, white)';
} catch(e) {
// Ignore failures.
}
var supports = element.style.background.indexOf('-moz-linear-gradient') > -1; // Did it accept?
element.style.background = oldstyle; // Restore old style.
return supports;
}
You should check for -moz-background-size (which was introduced in Firefox v3.6). The inference won't be picked up by other browsers since the property is prefixed.
if ('MozBackgroundSize' in document.body.style)
This is how MooTools detects Gecko (Firefox) engine (I'm "paraphrasing" slightly)
gecko = (!document.getBoxObjectFor && window.mozInnerScreenX == null) ? false : ((document.getElementsByClassName) ? 19 : 18)
So if it's FF it'll return 19 or 18, I believe 19 is 3.x and 18 is 2.x
And apparently FF3.6 stopped supporting document.getBoxObjectFor, so to detect 3.6 I basically do
isFF36 = gecko && !document.getBoxObjectFor
Works like a charm from a few tests I did.
If you're not using MooTools you can probably combine the two into one statement that would return something like false or 'ff' or 'f36' but I'm too lazy to work through that logic :)

Popup window not opening on IE7

Hi Javascript gurus, I have this Javascript code which is working fine on Firefox , but it is not working on IE 7. Any ideas why?
Here is the code
function TestWindow()
{
SimpleWindow('Default.aspx', 'Simple Test', 200, 200, 'yes')
}
function SimpleWindow(mypage,myname,w,h,scroll)
{
var win= null;
var winl = (screen.width-w)/2;
var wint = (screen.height-h)/2;
settings='height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',toolbar=no,location=no,status=no,menubar=no,resizable=no,dependent=no'
win=window.open(mypage,myname,settings)
if(parseInt(navigator.appVersion) >= 4)
{
win.window.focus();
}
}
You may have realized that IE is giving the error "Invalid argument."
IE doesn't seem to like window names with spaces in them. Change 'Simple Test' to 'SimpleTest' etc.
For myname parameter use only a-zA-Z0-9 characters. IE doesn't like any other, especially whitespace characters.
Check popup blockers
Check for reserved words. Your parameter name "scroll" is probably messing up your code in IE.

Is there a cross browser way of setting style.float in Javascript?

Usually, if you need to set a style attribute in JavaScript, you say something like:
element.style.attribute = "value";
There are slight variations but usually the attribute name is a similar, albeit camelcased, version of the HTML attribute name.
The problem for me is that the float attribute doesn't work. Float is a keyword in JavaScript and so style.float makes all the JavaScript for the page break. I looked in MSDN, and it said to use styleFloat like so:
element.style.styleFloat = "value";
That only works in IE. Firefox, Safari, Chrome, Opera - none of them seem to have an answer. Where am I going wrong? There has to be a simple answer to this.
Use cssFloat as in...
element.style.cssFloat = "value";
That works in everything except IE 8 and older, but you can always detect the browser and switch, or just set them both. Unfortuantely, there is no way to set just one style value to work in all browsers.
So to summarize, everyone you need to set the float, just say:
element.style.styleFloat = "value";
element.style.cssFloat = "value";
That should work everywhere.
better:
element.style.styleFloat = element.style.cssFloat = "value";
This is a function sniff approach:
if (typeof elmt.style.cssFloat != "undefined")
elmt.style.cssFloat = "none";
else
elmt.style.styleFloat = "none";
But usually we don't need to bother with this detection. I have tested user2719099's approach with Chrome as below:
elmt.style.cssFloat = elmt.style.styleFloat = "none";
console.log(elmt.style.cssFloat, elmt.style.styleFloat);
And the result is quite good in the console:
none none

Categories