Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

switching css for Javascript is disabled

I´m having a problem switching css when Javascript is disabled.

I have this code:

<style type="text/css">.nonjsonly{display:none;}.jsonly{display:inline;}</style>
<noscript><style type="text/css">.nonjsonly{display:inline}.jsonly{display:none}</style></noscript>

Witch is working right now, but W3C doesn´t approve it, as noscript is illegal in html head (And the code is in head).

Any idea how it can be made?

Thanks in advance

like image 838
Pablo Avatar asked Dec 17 '22 07:12

Pablo


2 Answers

A more appropriate way to handle this is to place your non-js CSS first, without any <noscript> tag, followed by a script which loads a stylesheet for JavaScript-capable clients. The JS-capable css should then cascade to override the basic sheet.

<style type='text/css'>
  /* baseline CSS for all clients */
</style>

<!-- Then a script loads an additional stylesheet which cascades to override the baseline -->
<!-- Obviously, won't get loaded by noscript clients -->
<script type='text/javascript'>
  document.write("<link type='text/css' rel='stylesheet' href='/path/to/js-friendly.css' />");
</script>
like image 135
Michael Berkowski Avatar answered Dec 27 '22 13:12

Michael Berkowski


Put the default css first:

<style type="text/css" src="default.css" />

so the non-JS styles apply to everyone. Then use some JS to dynamically load the "js-enabled" styles:

<script type="text/javascript">
    css = document.createElement('link');
    css.setAttribute('rel', 'stylsheet');
    css.setAttribute('type', 'text/css');
    css.setAttribute('href', 'js-styles.css'); // change as needed
    document.getElementsByTagName('head')[0].appendChild(css);
</script>

which will override the non-js styles.

like image 27
Marc B Avatar answered Dec 27 '22 15:12

Marc B