Modernizr

Contact Us or call 1-877-932-8228
Modernizr

Modernizr

The example above, in which we tested whether the user visiting our canvas.html page was using a brower that supported canvas drawing; we did this through some custom JavaScript code:

var canvas=document.getElementById("my-canvas");
if (canvas.getContext) {
	//...
}

It worked fine for testing the current user's browser for the canvas feature. But what if there were some other features we wanted to detect? And what of the issue of the code needed to detect those features changing over time? Luckily, there's a library for that: Modernizr.

Modernizr, as described on their site, is "a collection of superfast tests - or 'detects as we like to call them - which run as your web page loads, then you can use the results to tailor the experience to the user."

How Modernizr Works

Visiting Modernizr's download page offers us the option of selecting which features we wish to detect:

Modernizr download page screenshot

We select the feature(s) we wish to detect, then download the custom-built JavaScript file. Once including this JavaScript file in our page, we can then reference the Modernizr object to test support for a given feature:

if (Modernizr.canvas) {
	//draw on canvas
}

The next demo gives an example of the use of Modernizr:

Code Sample:

NavigatorHistoryLocation/Demos/canvas-modernizr.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Canvas</title>
<script src="modernizr-custom.js"></script>
<script>

function drawPath() {
	if (Modernizr.canvas) {
		alert("Canvas Supported.");
		//create your awesome drawing here
	} else {
		alert("Canvas Not Supported.");	
	}
}
</script>
</head>
<body>
<canvas id="my-canvas" height="200" width="200">Your browser doesn't support canvas.</canvas>
<button onclick="drawPath();">Draw</button>
</body>
</html>

Code Explanation

We downloaded Modernizr - a custom build, in this case, in which we ask to detect only the canvas feature - and included the downloaded JavaScript file in our page. We can then use Modernizr to test for canvas support: Modernizr.canvas.

Next