apamphilon

JavaScript Detection

In this post I am going to be looking at how to detect if the user has JavaScript enabled. I will then be looking at one method of what to do if  JavaScript is disabled.

In order to do this I will be using the hugely popular feature detection library ‘Modernizr’. You can read about this library and how to include it in your build here https://modernizr.com/

For the most part you just need to build a custom modernizr file and then download and include it in your build.

You can download my build below (although I must warn you that I haven’t updated it in a while)

Include this file in your header like so

<script src="PATHTOFILE/modernizr.min.js"></script>

We then need to add a class to the body like so

<body class="no-js">

On page load, if JavaScript is detected Modernizr will remove this class from the body. So essentially this means that we can use this class as a style hook for when JavaScript is not enabled.

For example in SASS we could write:

h1 {
    display: none;
    .no-js & {
        display: block;
    }
}

or in css:

h1 {
    display: none;
}
.no-js h1 {
    display: block; 
}

Comments: