Wednesday, 7 March 2012

JavaScript: check if it is enabled or not

   


Web developers rely heavily on JavaScript. However, a whole web site project might be jeopardised if in the end the final user's browser has JavaScript disabled. In those cases a good web developer plans good fallbacks accordingly. But, how can we check if JavaScript is enabled?

Believe me it is very simple. When I found the following solution a long time ago, I was amazed by its simplicity and effectiveness.

As a start, we need to insert a form in the body of our page. I would suggest, we put it at the very beginning of the page:
<form name="js" id="js">
  <input type="hidden" name="JSstate" value="false">
</form>

The form has an hidden input box with a name, "JSstate", and a value, "false". If JavaScript is enabled, we know we can change the value of the input box. If JavaScript is disabled, we won't be able to change its value.

Now you begin to understand the logic, don't you?

We just put a simple JavaScript snippet in the head of our document:
<script language="JavaScript">
<!--
  document.js.JSstate.value ="true"
-->
</script> 
The above code will change the value of the hidden input box to "true", only if JavaScript is enabled. If JavaScript is disabled, the above code won't be executed and the value will remain "false".
By inspecting the input box value, we will then know if JavaScript is enabled or not for the target browser.

Have a nice day and happy coding!

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.