144

Detect css with jquery

I was trying to get a custom flash replacement thing working the way I wanted, and realized that the replaced flash titles looks really bad in text browsers that still supports javascript (try viewing a sifr powered page with CSS turned off in Firefox). So I came up with a simple javascript written in jQuery that can detect if the browser has CSS support:

  1. function hasCSS() {
  2. var _d = document.createElement('div')
  3. _d.id = 'css_test'
  4. $('body').append(_d)
  5. $('#css_test').css({width:'1px',height:'1px',display:'none'})
  6. var _v = ($('#css_test').width() != 1) ? false : true
  7. $('#css_test').remove()
  8. return _v
  9. }

This is the idea behind the script:

  1. Create a 1×1 pixel element with a display:none style
  2. Append it to the body
  3. Check if the offsetWidth of the element is 1px
  4. Delete the element
  5. Return the boolean result

Use it like this (example):

  1. $(document).ready(function(){
  2. if(hasCSS()) {
  3. // do something
  4. }
  5. })

I’m not sure this is the way to go but perhaps someone else would find it useful in some other context. Many javascript behaviors and events are based upon the fact that the user agent also supports CSS but that might not always be the case. It works in the browsers I tested in (IE/win, FF, Safari etc.). Have a look at this page without CSS enabled to see the result (you might have to press the refresh button once).