How to detect whether CSS enabled or not using Javascript


#1

Hi,

I just want to know whether CSS has been enabled or not in my browser using Javascript.

Here is the sample code i used.But its not working properly.

isCssSupported = function()
{
var _d = document.createElement("div"), _v;
d.id = "csstest";
_d.innerHTML ="test";
if(_d){

	_d.style.width = "1px";

	document.body.appendChild(_d);
}

var xx = document.getElementById("css_test");

_v = (xx.style != 'undefined' && xx.style.width != '1px') ? false : true
//document.body.removeChild(_d);

return (_v) ? "yes" : "no";

}

its returning "yes" always. Can anyone please help me to fix it up?

Thanks in advance,
Priya


#2

No no! Please read up on progressive enhancement or give a specific reason as to why you need to detect whether CSS is on or off.


#3

I just want to detect whether user has enabled css or not for a strategy


#4

Testing if CSS is enabled or not from JavaScript would be pointless.

Your visitors are going to belong to one of the following three groups.

  1. HTML enabled, CSS enabled, JavaScript enabled
  2. HTML enabled, CSS enabled, JavaScript disabled
  3. HTML enabled, CSS disabled, JavaScript disabled

The only exceptions would be people running 15 year old browsers that don't support CSS but those are not going to support most of the JavaScript either - fortunately that person (there's only one of her) isn't all that likely to visit your site.


#5

Haven't had the need to do this, but the way I'd go about it is have a dummy element that's hidden and apply a property to it.

<head>
<style type="text/css">
#checkDummy{margin-top:1px; display:none;}
</style>
</head>
<body>
<input type="hidden" id="checkDummy" value="">
<script type="text/javascript">
function checkDummy()
{	
	var val;
	var el=document.getElementById("checkDummy");
	if(document.getComputedStyle)
		val=document.defaultView.getComputedStyle(el,null).getPropertyValue("margin-top");
	else
		val=el.currentStyle.marginTop
	
	if(val=="1px")
		alert('style sheet loaded')
	else
		alert('style sheet not loaded')
	
}
checkDummy();
</script>
</body>

I occasionally turn off style sheets/images in browsers I use to print pages. Sometimes reading plain content is easier on the eyes also. Interesting you want to write a script for something like this, you've got me curious what it's for.


#6

Thank you Bals.... I tried with as like your suggestion...but its not working correctly in Firefox frowning


#7

This is just a bad way of thinking - could you please give some detail as to what you're trying to accomplish? Almost no professional developer does any kind of detection of whether JS or CSS is enabled, as you should build from the ground up and provide your basic content in html, and built upon that layer with styles and then behavior.


#8

I'm curious about how this might be accomplished, and I don't mind sharing my reasons. I've got a page that uses jquery to present my semantically marked-up content as tabs rather than a long list of section one below the other. As is common, it does it by hiding/showing the relevant divs, and the 'tab-tops' themselves are a styled, unordered list.

If the visitor has javascript disabled then they see the content sections one under the other as if I'd never gone down the tab route, and the list at the top (styled more as a regular list with js off) becomes a handy set of skip links to jump the user down to the relevant section. So the js is progressive enhancement, as SoulScratch quite rightly advocates.

Similarly, if styles are also disabled then the use gets the same thing (list of skiplinks followed by sections in simple linear order), just unstyled.

The problem is that if the user has styles disabled but javascript ON, the skiplinks don't work, because the javascript that makes the tabs work requires a return: false to stop the page jumping downward when the 'tab' (whose href is of course a #fragment) is clicked.

I can create helpful workarounds for 'js:on, css:off' users who might wonder why the skiplinks don't work, but my options for doing so expand if I can detect whether styles are on or off via js. As far as I can see, none of this contradicts the progressive enhancement ethos; everything is a non-destructive addition to the basic semantic xhtml.

I note that felgall reckons that nobody would be browsing with css disabled and javascript enabled. Can you tell me why that is felgall? (Not being snippy, I'm genuinely interested because maybe there is a factor I overlooked).

Looking forward to people's views.


#9

You have actually answered your own question. People do not turn off CSS and leave JavaScript enabled because it breaks a large percentage of web pages in the way you have just described. Plus the fact that the way web pages are built you have HTML enhanced by CSS that is further enhanced by JavaScript and it makes no sense to turn off the m iddle layer since then as you have seen the javaScript isn't going to dunction correctly because what it is intended to work on is no longer there.


#10

Hi felgall, thanks for responding. I agree, it makes no sense to me for a visitor have javascript on but css off, for all the reasons that you state. On the other hand, many of the techniques I use for making my web pages as 'bulletproof' as possible as done in order to accommodate combinations of user choices/browser settings that I would never make myself. So I was just wanting to make absolutely sure that I wasn't ignoring a user preference that, whilst unusual, would not nevertheless crop up. (The average user will, of course, neither know of nor care about the triple-layered markup/styling/functionality web standards way of building pages, and nor should they, so that probably isn't going to be a factor in their decision of what to leave on or turn off in their browser).

To go back to where this all started, though -- js detecting css on/off status -- it's certainly looking like a whole lot of added nonsense for a very VERY small group of visitors (if they even exist at all -- I do accept your point that perhaps NOBODY will have js on and CSS off). So I'm sticking with my initial solution, which is to use javascript to dynamically insert a message explaining to the user why the skiplinks don't work for them, and then hide it using css. If js is off then the message doesn't get inserted at all (because it's not needed); and if it IS inserted then it's only seen in the one situation where it's relevant: when styles are off. (Situations where javascript is on but the visitor is using their own custom stylesheet... hmmm. Too bad, I think).

In any case, I hope that I've at least found an instance where detecting css status with javascript is not a direct contradiction of Progressive Enhancement, but in fact embraces that philosophy. Thanks again for your valuable input.


#11

I'm replying to this old thread because it came up in a Google search and I'm mortified by the advice that is being dispensed here.

I think the advice given to the original poster in this thread is ridiculous. Yes, it is highly unlikely that users with JS enabled will disable CSS but it is not impossible. If a user does do this then it can cause breakage if you do not check for it.

You can detect CSS being disabled from JS like this:

var cssdisabled = false; // must be proven otherwise
var testcss = document.createElement('div');
testcss.style.position = 'absolute';
document.getElementsByTagName('body')[0].appendChild(testcss);
if (testcss.currentStyle) var currstyle = testcss.currentStyle['position'];
else if (window.getComputedStyle) var currstyle = document.defaultView.getComputedStyle(testcss, null).getPropertyValue('position');
var cssdisabled = (currstyle == 'static') ? true : false;
document.getElementsByTagName('body')[0].removeChild(testcss);

After executing that snippet in your code, simply check to see if the boolean cssdisabled is false before doing anything that depends on CSS to be loaded. I often use this technique to disable most of my JS features for users without CSS enabled. I've tested it in IE5.5, IE6, IE7, IE8, Firefox1, Firefox2, Firefox3, Safari3, Safari4, Opera9, Chrome, and Konqueror.

In any case, advising the poster not to bother with this is lazy, irresponsible, and disrespectful. He asked a specific question. He deserved an actual answer, not to be told his goal is pointless when it is demonstrably not.


#12

And since 99.99999% of sites don't checkl for it and will therefore be broken as a result being the one site in 10,000,000 that isn't broken for those people isn't going to be all that meaningful.Anyone setting up that particular combination would not keep it for any length of time simply because it would break the functioning of so many sites. In fact the majority of those who do so are those who have that 1 in 10,000,000 site that is actually testing that combination in order to make sure that their site works when they turn off CSS in their own browser to break everyone else's site.

The numbero of extra visitors you will lose through having that small amount of extra code in your page to slow the page from loading will exceed the number of visitors you will fix the site for through using that code.


#13

That is absurd. A few extra lines of JS is not going to make a significant difference in site speed, especially with things like gzip compression, minification, or both.

The odds that the extra code would cause you to lose users for site speed reasons are even more remote than a user having JS enabled and CSS disabled.

If your position is that the odds of the latter are insignificant, then you should be equally unconcerned with the odds of the former due its greater unlikelihood. Your position is logically inconsistent.


#14