views:

238

answers:

4

i want to do it from external css file. i have a div#abc in main css but i want to set display none for this div only if javascript is disabled

+2  A: 

How about

<noscript>
  <style type="text/css">
  div#abc { display: none; }
  </style>
</noscript>

? If you really want to do it in an external CSS file, move this into no_js.css and reference this file in a link element instead of the style attribute.

Mostly however, it is more convenient to go the other way round: Set the defaults for disabled JS and then let JS change class names (for example) to update the style. jQuery example:

$(document).ready(function () {
  $('.fancy_user_interface_element').addClass('additional_js_style_class');
});
Boldewyn
ok but i should put this code in <head>?
metal-gear-solid
Well, it *works* also in `head` (or `style` elements in body). If you're bound to validate your page, I'd suggest you take a look at the second part of my answer.
Boldewyn
Or you can JS let create the elements (`document.write()` or DOM methods). This way they are not even in the document at all without JS.
Boldewyn
A: 

Put the element you want to appear, inside of the noscript tag, and it will be displayed only if javascript is disabled.

Tor Valamo
+1  A: 

I would make the div style="display: none;" by default then show it with javascript.

<div id="abc" style="display: none;">
 ...
</div>

<script type="text/javascript">
    $(function() {
        $('#abc').show();  //using jQuery
    });
</script>

This way, if you don't have javascript enabled, the div won't be shown. I've shown it using inline CSS but you could also do it with a CSS class and simply remove the class from the element.

 <style>
    .requires-javascript { display: none; }
 </style>

 <div id="abc" class="requires-javascript">
     ...
 </div>

 <script type="text/javascript">
     $(function(){
         $('.requires-javascript').removeClass('requires-javascript');
     });
 </script>

This way would make it work with a single jQuery statement for all elements on the page that require javascript.

tvanfosson
yeah, good idea and i think this method is more semantic than <noscript>
metal-gear-solid
A: 

What you would do is have an event in your javascript that would set the style of the rule from hidden to unhidden. Have the CSS always set that element as hidden. If they have javascript turned off, it never unhides it and thus it stays hidden by the CSS.

Anthony