Monday, March 30, 2009

Use different CSS rules / styles in JavaScript or jQuery enabled browsers

This is a simple yet very useful and powerful technique. Using different CSS rules in JavaScript or jQuery enabled browsers lets you customize your website style for JS enabled and disabled browsers using only CSS. Thus you separate concerns of styling and business logic into CSS and javascript. This lets you concentrate on your goals and not styling in your javascript code for example.

All you need to do is to add some class or id to body element using javascript/jquery to specify that javascript/jQuery is available. Then define two rules in you CSS files for js enable and disabled browsers.

Here is an example for Javascript enabled browser:

document.getElementsByTagName("body")[0].setAttribute("class", "js");

And in your CSS file:

.someClass{
    display:block;
}
.js .someClass{
    display:none;
}

Why do I need to have a different CSS styles for jQuery/javascript enabled browser you might ask. Consider you have a drop-down menu on your website’s sidebar and you would like to use jQuery/Javascript to make it drop down on mouse hover. You don’t want to hide (display:none) all submenus’ by default. That would make your website not accessible if user has disabled Javascript on his/her browsers.

Similar to previous example, we can use difference CSS style for jQuery enabled browsers.

if(jQuery){
    jQuery("body").addClass("jq");
}

And in your CSS file:

.someClass{
    display:block;
}
.jq .someClass{
    display:none;
}

6 comments:

  1. very good tip, as simple as it is, i have not thought about it....

    ReplyDelete
  2. Neat trick. Thank you for sharing.

    ReplyDelete
  3. Excellent piece of code - thanks for this! I initially got a bit confused as I thought "body" meant the element class name - I'm new to jQuery!

    ReplyDelete
  4. Hi there,

    This sounds like exactly what I need. I understand the css portion, not the rest. Not a very good programmer myself, sorry. If you have 2 sec to spare.

    - Do I need to add the "function isipad" in the head? (found here: http://jquery-howto.blogspot.com/2010/10/javascript-to-detect-ipad-visitors.html)
    - Where does the "document.getElementsByTagName" above go? How does it interact with the javascript?

    If you have an example, it would be great.

    Thanks, Ge

    ReplyDelete
  5. The same does modernizr.
    But it's excellent tip if you dont care for IE :-)

    ReplyDelete