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;
}