Feature detection

Last updated on
1 March 2018

Drupal 7 will no longer be supported after January 5, 2025. Learn more and find resources for Drupal 7 sites

Browsers of all types connect to the web, and the diversity is only increasing. It used to be acceptable to specify which browser parameters (e.g. browser maker or screen size) the user should adopt to properly view your content, but this is no longer the case. Instead, it is better to adapt the web page to the users' individual browsers, based on the presence or absence of specific features. This is where the concept of feature detection comes from.

Think of feature detection as a way of fingerprinting a web browser. Just like two people with the same name, two devices running the same browser will produce different fingerprints.

Modernizr

Modernizr is the most popular feature detection library. It is a small JavaScript library that checks each user's browser features on every page load. It then prints the outcome of each test as a class inside the <html> tag of each page, allowing stylesheets that contain rules for both outcomes to "choose" a set of features. Modernizr provides detailed docs on their website.

Example

Touch devices often need very different interfaces than non-touch devices. Instead of relying on user-agent sniffing, it is more robust and future-proof to check for the presence of touch events and then develop CSS or JavaScript solutions for both outcomes.

Conditional CSS

When Modernizr is executed each page load, by default it injects the results of all its tests into the <html> class attribute. If a feature is not supported, it is prefixed with no-.

.touch nav li {
  display: block;
  padding: .5em 1em;
  background: #456;
  border-radius: 5px;
}
.no-touch nav li {
  display: inline;
  float: left;
}

JavaScript

JavaScript is a little more obvious because conditionals are one of its fundamental features.

if (Modernizr.touch) {
  $('nav').touchNav();
}
else {
  $('nav').notouchNav();
}

Drupal integration

Drupal's Modernizr module harnesses the power of Modernizr and provides additional integration, allowing Modernizr to be fully aware of your unique Drupal installation.

Help improve this page

Page status: No known problems

You can: