views:

450

answers:

5

I'm trying to accommodate users without JavaScript. (By the way, is it worth the effort nowadays?)

In one html file I'd like part of it execute if scripts are ON, and another part if scripts are OFF.
<noscript> tag lets me do the former, but how to achieve the latter? How can I mark a part of html so that it is not parsed by browser if scripts are OFF?

+8  A: 

Default the bits you want to hide as styled as

display:none

and switch them on with jQuery/javascript

John Nolan
onready event is a good way to go
Ismael
+1  A: 

jQuery way:

$(document).ready(function(){
  $("body").removeClass("noJS");
});

(psuedo css)

body
 .no-js-content
  :display none
body.noJS
 .main
  :display none
 .no-js-content
  :display block

html

<body class="noJS">
 <div class="main">
  This will show if javascript is activated
 </div>
 <div class='no-js-content'>
  This will show when javascript is disabled
 </div>
</body>
DFischer
+2  A: 

here's a video tutorial on how this can be done with jQuery:

http://screenr.com/ya7

Natrium
+5  A: 

By the way, is it worth the effort nowadays?

Yes, it's worth worrying about accessibility. You should use progressive enhancement where possible, i.e. make a basic version that works without scripting and then add the scripting functionality on top of it.

A simple example would be a pop-up link. You could make one like this:

<a href="javascript:window.open('http://example.com/');"&gt;link&lt;/a&gt;

However, this link wouldn't work if someone, say, middle-clicked or tried to bookmark it, or had scripts disabled etc. Instead, you could do the same thing like this:

<a href="http://example.com/" 
   onclick="window.open(this.href); return false;">link</a>

It's still not perfect, because you should separate the behavior and structure layers and avoid inline event handlers, but it's better, because it's more accessible and doesn't require scripting.

Reinis I.
You don't even need JavaScript for that. Just name your target (or use 'target="_blank"')
Joe
I don't think that was the point Reinis was getting at
roryf
+2  A: 

If the content only makes sense when Javascript is enabled, then it should be inserted by the Javascript directly rather than being rendered. This could either be done by simply having HTML templates as strings within your Javascript, or using Ajax if the HTML is more complex.

As mentioned by Reinis I. this is the idea of Progressive Enhancement.

Regarding the CSS techniques of using a class name on the body tag, I would advise doing this the other way round and adding a 'js-enabled' class to the body tag with Javascript that would alter the page CSS. This fits in with my above comment about keeping all initial HTML 'non-Javascript friendly'.

roryf