Show and hide if javascript is enabled

An alternative to using noscript can be in the form of a hide and show function from our ever popular jquery library. Our old way of doing such a function may look like the following:

<noscript> You need to enable javascript for this to work </noscript> <p><a onclick="return addTotalProducts();">Calculate total</a></p>

A better and more cleaner approach would be do the following:

<p class="noscript">You need to enable javascript for this to work</p> <p><a class="js" id="calculateTotal">Calculate total</a></p>

First of all we have moved our onclick function out of our link element. We can use an unobtrusive javascript way to perform such actions. But we really need to look at is the js-hide and js-unhide classes and what they do.

The way that this works is that we should assume that javascript is disabled. This could happen for many reasons including a company that forces this to happen as they are concerned about viruses and other malicious forms of attacks, a user could decide that browsing the internet is safer with javascript disabled or a user could even be using a device that doesn't have javascript. Whatever the reason is doesn't concern us, what we need to do is not create any buttons that requires javascript without first checking javascript is enabled.

The CSS for this type of approach is as follows:

.js { display:none; }

This simply hides any elements that contain the class name .js-unhide. The jquery code for this to work is:

/*** hide and show objects that require javascript ***/ $('.noscript').hide(); $('.js').show(); /*** end ***/

The above code will now hide our noscript element (the element that contains the js-hide class name) and will show the element that requires javascript (the element that contains the js-unhide class name). This effectively is an alernative to using the noscript tag and shows and hides elements depending on if the user has javascript enabled.