Skip to content Skip to sidebar Skip to footer

How To Hide An Element To Be Toggled With Jquery While Maintaining Progressive Enhancement

All the answers I could find recommended adding display:none to css... but for a user without javascript, they will never see the element. jQuery(document).ready(function($){

Solution 1:

to prevent the javascript FOUC and let your page fully accessible you should apply a .no-js class in <html> element and then use that class to style your elements, exactly as html5 boilerplate+modernizr do

#toggleElm { display: none; }
.no-js#toggleElm { display: block; }

of course you have to remove that class via javascript soon in the <head> of your document, with a script like this

<script>
    (function(d) { 
        d.className = d.className.replace(/(^|\b)no\-js(\b|$)/, 'js');
    }(document.documentElement));
</script>

so if javascript is enabled, it will turn the .no-js class into .js class.

Using this approach, your page is still accessible even when javascript is not available, because in that scenario the last CSS rule will be applied, leaving your elements visible and accessible.

Solution 2:

An element is registered in the DOM as soon as it's closing tag has been parsed.

Therefore, you can hide the element straight after that tab;

<divid="toggleElm">Foo</div><script>// Note: No $(document).ready()!
    $('#toggleElm').hide();
</script>

Obviously this depends on jQuery being loaded already (i.e. not being included at the bottom of the page). If this is the case, revert to plain ol' JavaScript:

<divid="toggleElm">Foo</div><script>document.getElementById('toggleElm').style.display = 'none';
</script>

Solution 3:

If you don't want to wait for the document to be ready, don't wait for the document to be ready.

<pid="foo">Stuff...</p><script>document.getElementById('foo').style.display = 'none';
</script>

Post a Comment for "How To Hide An Element To Be Toggled With Jquery While Maintaining Progressive Enhancement"