6

I want to execute a certain code in jQuery if the browser is lower than IE9. And yes, i already know about

<!--[if ... IE ]> <![endif]-->

But what i want is to check this condition within the scipt tag and with jQuery document.ready

<script>
    $(document).ready(function(){
        //code to check if lt ie9 
    });
</script>
André Dion
  • 19,231
  • 7
  • 52
  • 59
melvindidit
  • 410
  • 2
  • 5
  • 15
  • possible duplicate of [Detect IE version in Javascript](http://stackoverflow.com/questions/10964966/detect-ie-version-in-javascript) – JJJ Aug 09 '13 at 11:39
  • Have you considered using feature detection rather than browser detection? – Spudley Aug 09 '13 at 11:54

2 Answers2

14

You can target older Internet Explorer versions (<= 9) through classes on the <html> element...

<!--[if lt IE 7]>  <html class="ie ie6 lte9 lte8 lte7"> <![endif]-->
<!--[if IE 7]>     <html class="ie ie7 lte9 lte8 lte7"> <![endif]-->
<!--[if IE 8]>     <html class="ie ie8 lte9 lte8"> <![endif]-->
<!--[if IE 9]>     <html class="ie ie9 lte9"> <![endif]-->
<!--[if gt IE 9]>  <html> <![endif]-->
<!--[if !IE]><!--> <html>             <!--<![endif]-->

... and then check if <html> has the class .lt9 or .lt8 — whatever version of Internet Explorer you are targeting:

if($('html').hasClass('lte9')) { /* LTE IE9 */ }

However, I would suggest using Modernizr feature detection instead of checking for a specific browser.

Daniel
  • 1,802
  • 2
  • 24
  • 41
  • This is the most fail-safe and future-proof approach that lends itself to forking for IE both in JavaScript and CSS *and* is treated as HTML comments by all other browsers. – André Dion Aug 09 '13 at 12:07
2

Use feature detection instead of browser detection. i.e. http://modernizr.com/

Aegis
  • 1,679
  • 11
  • 12
  • 2
    Dear _Aegis_, please avoid link only answers, 'cause valuable information will belost when the link is outdated. Instead, give an additional description of your core idea here. Thx! – Trinimon Aug 09 '13 at 11:55