Do something if web browser is IE, in JavaScript - javascript

Where do I place this script in my HTML for it to work? And what changes do I have to make to it?
<script type="text/javascript">
var browser=navigator.appName;
if(browser="Microsoft Internet Explorer")
{
document.getElementById("html").innerHTML="\
<body><p>Your browser is IE.</p></body>";
}
</script>

Could I make a slightly alternate suggestion, skipping the spoofable UA string, and using a Microsoft-implemented (and standards-compliant) strategy:
<!--[if ie]>
<script type="text/javascript">
document.getElementyId("html").innerHTML = "<body><p>Your browser is IE.</p></body>";
</script>
<![endif]-->
To use this put it in the head of the document. I don't think it can be placed inside script tags (since it's based on html comment syntax, not JavaScript).
This uses conditional comments (Quirksmode.org link).

If at all possible, I would suggest avoiding direct browser detection.
Almost every case where someone wants to detect a specific browser (usually IE), it is because there is a particular feature that they want to use which isn't available in that browser, or has bugs.
But browser detection fails as a strategy here for a number of reasons:
You don't know whether a future version of that browser may correct the problem, in which case your code to fix the issue may itself cause problems.
If another browser also has a problem with that feature, you would have to detect that browser as well. Taken to the logical extreme, since no two browsers have exactly the same set of features, you end up having to detect every possible combination of browser, version and operating system.
Browser detection is virtually impossible to guarantee to be accurate. Most browser detection scripts are based on hacks that trigger quirks that only affect a particular browser, and most are pretty un-reliable.
Even just IE detecting isn't good enough. There is a big difference between IE6, IE7 and IE8. And IE9 is just around the corner, which will be massively different again.
So what should you do instead of browser detection?
Detect the feature. There are a number of ways of doing this, but the best solution I know of is a script called Modernizr. Place this script in your site, and your page will be given a bunch of CSS classes and Javascript properties which you can use to determine whether a given feature is available or not.For example, if you want to use gradients on your site, most browsers can use CSS for this, but IE and older versions of other browsers cannot. For these browsers you easily can use a background image instead. Modernizr will give you a CSS class of either cssgradients or no-cssgradients, and you can style these two classes accordingly.
Add the missing features to the browser. This is more tricky, but for certain features it can be done, particularly for IE. A good example is CSS3Pie which is a hack that allows IE to use the CSS border-radius feature (and one or two other features too) which is available in all other browsers. There are whole range of other little scripts like this which can improve the functionality of IE.
Use a library like JQuery which does all this work for you. With JQuery, you can be much more confident that most of your Javascript code is going to work across all browsers.
If you must use browser detection to tell if the user is running IE (and I accept that there are some occasions when it is necessary), then use conditional comments, as per #David Thomas's answer. But do so sparingly, after considering any other ways around it.

if(browser=="Microsoft Internet Explorer")
== for comparison, = for assignment
Place it in the head tags.

Related

Only allow access to the site for HTML5 Users [duplicate]

What is the best way to detect browser compatibility for HTML 5 syntax? And prompt the user if the browser is not compatible?
I understand the tutorial which shows how to test browser compatibility for HTML5. But I am curious to know if that is the only way? Do I need to inspect each and every element?
Have a look at Modernizr:
Taking advantage of the new capabilities of HTML5 and CSS3 can mean
sacrificing control over the experience in older browsers. Modernizr 2
is your starting point for making the best websites and applications
that work exactly right no matter what browser or device your visitors
use.
Thanks to the new Media Query tests and built-in YepNope.js
micro-library as Modernizr.load(), you can now combine feature
detection with media queries and conditional resource loading. That
gives you the power and flexibility to optimize for every
circumstance.
It has a lot of built in methods to test for browser features and provides a useful way of providing fallback code for when features you want to use are not supported.
More info: http://www.modernizr.com/
"HTML5 compatibility" is a very vague thing.
When people ask about HTML5 compatibility, they generally mean "what browsers support these new-ish browser features X, Y and Z which I want to use?"
There are a whole raft of features which have been added to browsers in the last couple of years, and which are now commonly referred to as "HTML5".
In fact, there aren't any browsers which support every new feature out there.
What you need to do is work out which features have wide enough support to make them worth using, which features you'd like to use but are happy to work around if you encounter a browser that doesn't support them, and which features you absolutely have to use to achieve what you want to do.
A fairly comprehensive list of new browser features, along with browser support charts for them all is available at http://caniuse.com/ (if you scroll to the bottom, you'll see in the overall compatibility table that the very best current browsers only support 89% of features they've tested. This will improve over time as new versions are released... but of course, also new features will be introduced too)
For determining at run-time whether the user's browser supports a given feature, you can use Modernizr. This is a Javascript-based tool which will give you a set of CSS classes and Javascript flags which tell you what features are supported. You can use this to trigger alternate behaviour in your site if the browser doesn't support a feature you want. (Modernizr also includes the HTML5Shim functionality, which allows IE to at least cope with HTML pages containing new HTML5 elements).
For more cross-browser compatibility, there are a whole range of hacks which have been written to allow older browsers (mainly IE to be fair) to support a range of newer features. You can see a fairly comprehensive list of them here: https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-browser-Polyfills
Obviously, trying to run more than a few of these at once in IE will severely impare your site's performance, but it can be handy if you need to support one or two features. My favourite at the moment is CSS3Pie, which gives IE6/7/8 support for CSS rounded corners, shadows and gradients.
Hope that helps.
Here is a tutorial of detecting HTML5 compatibility & capabilities :
http://diveintohtml5.ep.io/detect.html
There are alternative HTML5 detectors using similar techniques, but I would suggest to use Modernizr.
To sum up the "score" of HTML5, you can design your own "marking scheme". Sum up weighted score gives you the total score.
The simplest method : in JS you create a new element, and set the attributes to be a colorpicker (HTML5) in JS, and return the type of the element (it is a picker only if the browser ic HTML5 compatible) :
var element = document.createElement("input");
element.setAttribute("type", "color");
return element.type !== "text";
do I need to inspect each and every element?
Nope. Only the parts you want to use that aren’t backwards-compatible.
See Five Things You Should Know About HTML5, especially points 1 and 4.
I would suggest you can try using <audio>Anything within Audio tag here</audio>.
Any text written inside the between <audio> and </audio> will be displayed in browsers that do not support the <audio> tag.
Since the audio tag is newly added in HTML5.
This works on IE 11 (and hopefully other browsers too).
// Detect HTML v5 compatibility
var isHtml5Compatible = document.createElement('canvas').getContext != undefined;
It's a take from Clement's answer and the link from Shivan (http://diveintohtml5.info/detect.html). Clement's answer didn't work in IE 11.
In my case I use jQuery UI for everything so don't need Modernizr (also it seemed slower). Reading the rather negative "How to use Modernizr" blog comments supports this assumption.
But now jQuery have split browser compatibility between v1 and v2 development streams, its necessary for people wanting to support non-HTML v5 browsers to load EITHER the v1 or v2 jQuery core script at the start. So this "one liner" HTML v5 detection is perfect. Here's how I load jQuery properly using the result:
// Use jQuery v2 for HTML v5 browsers else v1 to support old browsers
var jQueryScriptPath = (isHtml5Compatible)
? "/Scripts/jquery-2.0.3.js"
: "/Scripts/jquery-1.10.2.js";
document.writeln("<script src=\"" + jQueryScriptPath + "\" type=\"text/javascript\"><\/script>");
If you vote this answer up please also vote clement and Shivan's answers too :-)

Support for turn.js in older browsers

I'm using turn.js for a page-flip effect, and it doesn't seem to work very well on IE7/IE8 (load up the website in IE7 mode and you can see for yourself).
What's the best way to support old browsers, while keeping the cool page-flip on modern browsers? (Note: I don't need the hot corners at all on IE, as I also have dedicated arrow links which flip the page via Javascript, similar to the turn.js demo.)
Do you have a sample of how you're applying turn.js? As in, do you have a link or how is your page structured? These are a good place to start.
More the the point of gracefully failing when you detect an older browser: There are multiple options, some make more sense than others depending on how much of the site is already done. First off, how does the site look with Javascript disabled completely? I know this isn't the case for IE7/8, but start there. Can it be used with no JS whatsoever? If the answer is "no," think of ways to make that answer "yes" if you can. This is always a good question when thinking about how to handle older browsers.
If you're early in the site's programming, or the content is laid out in a clear way, then you can work around the limitations of older browsers. A practice I try to follow is designing the site without JS or with as little as absolutely possible, and then program in functionality for "whizzing and banging" afterwards.
In your case, I would suggest something along the lines of: if you detect IE7/8 (or mobile browsers that may not be up to snuff, etc) then load in a secondary stylesheet with rules that give your content as much of the feel of the "original" as you can. Next, have the JS for the older browsers show/hide the pages of content instead of page-flipping them - this can be achieved with some divs on the left and right that move the page and then track the current page vs possible pages (are there any before this page? after this page?) in order to show/hide the navigation divs. turn.js just looks like fancy animations for the same thing, so you should be able to say "Hey, this browser is IE 7 or IE 8 - so, let's not initialize turn.js and just turn control over to the page previous and page next divs."

Javascript IE6 getElementsByTagName not working

I've got this example page where I'm trying to put the wmode of every youtube element inside the page to "transparent".
To do it I need to get all the "object > params" and "embed" tags in the page.
The page I link you works like charm in all the browser except for IE6 (haven't cheked the other IEs yet).
With IE6 I can't catch the "params" since document.getElementsByTagName('param') returns an empty object, but this doesn't happen with the "embed"!
It won't work with document.getElementsByTagName('object') as well
Here is the page http://dl.dropbox.com/u/4064417/provaJs.html
Any suggestion why it's not returning just the "param" tags?
Thank you in advance!
I recall some issue with <param/> tags and getElementsByTagName, but it's ages that I don't code in IE6. Instead of querying from document, trying to get the params calling getElementsByTagName from the <object /> itself and see if it helps:
var objects = document.getElementsByTagName("object");
for (var i = 0, object; object = objects[i++];) {
var params = object.getElementsByTagName("param");
alert(params.length);
}
I understand that you would like to keep your app backwards compatible, but this exercise runs counter-intuitive to the general direction of the industry and its efforts to put IE6 down to rest (even google has dropped support for IE6). Your time might be better invested if you focus on building a better web experience for pseudo-modern browsers instead of worrying about the legacy ones.
Food for thought - maybe use a browser detection script and encourage your users to upgrade so that they can experience your site in all of its modern glory :)
All that being said, ZER0's suggestion is dead-on. Find the "object" tags in the page, and then iterate through its children until you find the tag you're looking for. If you can't seem to grab the object tags with getElementsByTagName, you may very well have to iterate through the document.body.childNodes nodelist, checking for the typeof(N) or N.NodeName along the way.
If you must support browsers as old IE6, I would strongly recommend using a library such as jQuery rather than trying to access the DOM directly.
IE6 has a massive number of bugs and quirks that can break even the simplest and most innocuous of Javascript code. jQuery goes to great lengths to abstract these browser bugs and deficiencies away from the developer, allowing you to write code that works on all browsers.
For example rather than using document.getElementsByTagName('object'), you can use the jQuery code $('object'), which will give you the same end result, but will work around any bugs in whichever browser your end user is running.
jQuery does a whole lot more than just hide the browser bugs, of course, but if you're working with IE6, that alone is a good enough reason to use it.
(other libraries are of course available if you really don't like jQuery for some reason)

Writing CSS rules to different browsers, how? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Cross-browser CSS
Ok, so the question might be somehow a little confusing.
I'm gonna try to put it in a much simpler way so "you" can understand my
point of view.
All browsers are different. Every browser interprets the CSS rules
diferent, which drives to different results. Some times the results are good
other times and much often results are totaly unexpected. The case of IE can lead to the worst scenario possible!
Many often, developers are forced to detect the browser to apply a
specific css style!
This can be achieved with javascript support. Anyhow, some people say
that this method it's not enough to prevent disasters... others
think that the best way to deal with this problem it's to rely on
Object detection instead.
Well, I don't know which one is best...
Please feel free to give you opinion based on examples.
As always, thank you.
UPDATE
The case of IE can be very simple to deal with conditional statments but, safari can't be treated the same way! So I leave this link: http://quirksmode.org/js/support.html to clarify my point of view...
I personally don't believe in browsers sensing for CSS. In my opinion, it's a waste of time. It takes extra time to code, extra time to change, and creates an extra layer of headaches. Plus, when do you stop? AOL browser? Some random flavor of the day for a 15 year old version of linux used by 12 people in Iceland?
I also don't do hacks. Some will make their way in via Jquery's CSS or outside code I incorporate, but I don't personally write them. They don't validate, so they weren't meant to be in my mind. Javascript tricks are nice, but for styling I don't rely on them because they're not 100% reliable. If it's not gracefully degradable, it's not an option.
So, to combat the issues I do the following:
Clean, valid CSS
Reset (some of the time)
Grids (often, via Blueprint or 960.gs)
Dead reckoning of elements. This means avoiding the graphic designer mentality of 100% pixel perfection and designing for elements that can change as the web often does. Forget box model for a minute, fonts render differently too, and that will never change.
I avoid absolute elements like the plague. 99.5% of everything can be done relative if you try.
Cutting Edge...not bleeding edge. The cool new hacks are nice, but they aren't supported yet. So, they are last case scenario for me. It HAS to be this way for my large (well paying) corporate clients.
Intelligent design. Let's face it folks, if you design FOR THE WEB, you'll have an easier time making it so. If a designer converts a print design for the web, it's nearly always going to have --issues--. Can they be worked through? Sure, and it's profitable for us. But intelligent design in the first place solves all sorts of issues.
The name of the game is progressive enhancement, folks. If IE doesn't support rounded corners, they get square corners. After all, the standard rounded corners are valid HTML. If they have a problem with it, they can upgrade or change. Sound harsh? Sure it is. But we have a very clear standard (set by w3c) to maintain, and it's our job to do it. It's the only way to hit the mark on this moving target.
Two things. First, make sure you include a DOCTYPE. If you don't, browsers will default to quirks mode, and their interpretation of styles will be different. This way, you can minimize the different CSS interpretations of your page.
Second, I'll point out that IE (the big offender, in my experience) supports conditional comments, so you can include styles for specific IE versions like this:
<!--[if lt IE 8]>
<link rel="stylesheet" href="iehacks.css" type="text/css" />
<![endif]-->
All browsers are different. Every
browser interprets the CSS rules
diferent, which drives to different
results. Some times the results are
good other times and much often
results are totaly unexpected. The
case of IE can lead to the worst
scenario possible!
You should be able provide the exact same CSS to all browsers (I'm talking about CSS 2.1 here) and get consistent display, with the exception of IE6 and IE7 (and that's because they have too many bugs).
For those browsers, a common practise is to include a new stylesheet using conditional comments with specific fixes:
<link href="forAllBrowers.css" rel="stylesheet" type="text/css" />
<!--[if IE 7]><link href="ie7.css" rel="stylesheet" type="text/css" /><![endif]-->
<!--[if IE 6]><link href="ie6.css" rel="stylesheet" type="text/css" /><![endif]-->
The other scenario is when you're willingly using things that are only available in newer browsers.
In those cases, it's a good idea to use Modernizr to detect support for the shiny new feature you're using.
That way, you can provide a sane fallback for browsers which do not support the feature.
For singling out IE, particularly IE7 and 6 you can use conditional comments to load IE specific styles and or stylesheets.
Most bugs do have viable workarounds. Well formed and standards compliant html/css should display properly in all modern browsers.
IE Conditional Styles can help you work around imperfections in Internet Explorer.
Excluding JavaScript, there's basically two solutions to this problem. You can mix and match both.
The first solution is to determine the user's browser based on the header in the HTTP request. (Different platforms will allow you to do this in different ways - for example in ASP.NET, the Request object contains this information). You can then serve different physical CSS files depending on the user's browser.
The second way is to use a single CSS file that contains different rules for different browsers. The right rules are applied to the right browsers using various browser-specific hacks. Effectively, this means using CSS rules that only certain browsers understand. More information on this technique can be found here.
Well, for inline CSS, you can do specific hacks such as:
.myclass {
height: 100px; /* all browsers */
#height: 100px; /* MSIE browsers */
_height: 100px; /* MSIE >= v6.0 */
}
Alternatively, you can use comment style conditions within the page and include optional style sheets:
<!--[if gt IE 5]>
<style type="text/css">
.mystyle { height: 100px; }
</style>
<![endif]-->
Actually all current, modern browsers interpret CSS very similarly based on the standards. It's usally only IE (6, 7, 8) that make problems, especially if your HTML documents don't trigger Standards-Mode, thus:
Write your pages based on current HTML and CSS standards with a DOCTYPE.
For support of older IE, give them separate style sheets using Conditional Comments.
If there are differences between other browsers, there are usually workarounds. Ask abotu specific problems here or in your favorite CSS forum/group/list.
Just one word: Modernizr.
You should never change the styles based on user's browser, but based on the browser's resource allowed or not.

Is HTML 5 supported by all the main browsers?

I am looking at the custom attributes feature of html 5 here at this link
http://ejohn.org/blog/html-5-data-attributes/
This look like the perfect thing for when I am using jquery/javascript.
My question, Is HTML 5 supported by all the main browsers?
example
<li class="user" data-name="John Resig" data-city="Boston"
data-lang="js" data-food="Bacon">
<b>John says:</b> <span>Hello, how are you?</span>
</li>
Various portions of HTML5 are supported by the different browsers, for various definitions of 'supported'.
Several parts work right now, reliably. The data-* attributes you ask about in your question work just fine in every browser, even IE6; however, nobody yet supports the fun "dataset" method to access them. As long as you're fine with just grabbing them by the full attr name, you're golden. I use them to store state all the time in my webapps, as they're the officially blessed method for doing so.
Wikipedia has a good summary of the various support levels across browsers: http://en.wikipedia.org/wiki/Comparison_of_layout_engines_(HTML_5)
Parts of HTML 5 are supported by Safari, Firefox and Opera, but they are not necessarily incorporating the same parts.
It seems that Firefox is the most ahead, from my experience, but it will be years before the majority of browsers users use will support it.
So, until then we will need to continue trying to use it when we can, in browsers that support the new features, and having workarounds for users that haven't updated yet, or continue to use IE.
Use some services like
http://caniuse.com/
For example for your question - http://caniuse.com/dataset
As you can see all modern browsers support it
Also you can use something like http://modernizr.com/ in your code (it's already included in http://html5boilerplate.com/)
PS: just notified that this question is too old, but it was linked to some other question i checked before
No.
The Wikipedia page "Comparison of layout engines (HTML 5)" does a good job of listing which engines have implemented which parts of HTML5.
There is currently a lot of red boxes on those tables, and that is based on the latest development version, not the version most users will be using.
Full support of HTML 5 is a way off BUT...
Creating custom attributes is nothing new and is likely to work in all the main browsers - but test to be sure that it will work in your case.
We can use HTML 5 now, just not all of it. A lot of HTML 5 is about formalising the way that HTML is currently used and ensuring backwards compatibility - so if a feature works in browsers now, use it.
Almost no web technology is completely supported by any browser; no bugs, quirks or issues.
HTML5 is designed for backwards compatibility, and it will hardly break your site (take <input type=url> for instance - non-supporting browsers show an ordinary text box, Opera lets you select an URL from history/bookmarks). I'd go by the approach: develop, try in the browsers you need to support - if it works, awesome. If not, don't use it. Just like with other specs.
HTML5 isn't even close to being completely supported on any browser yet, and some browsers (notably the IE's) have no intention of supporting it at this time.
no, not yet. wait at least until gecko and webkit support it.
ps: you could use html 5 with data attributes anyway, if you need it for javascript purposes. or choose some other unused attributes (title, abbr, ...others?)
As of August 25, HTML 5 is still a working draft.
http://dev.w3.org/html5/spec/Overview.html

Categories