Bless you practical hipster gooseberry!

: Clippy, bash / zsh commands, CSS Color

Support/feature testing in JS

Method/Property

if ("method" in object) {...}

// Example (from MDN):
if("geolocation" in navigator) { ... }

Feature test

(from modernizr)

const hasSomeFeature = () => {
  try {
    // test something, eg. write to localStorage.
    return true;
  } catch(e) {
    return false;
  }
}

Check if element has property

Create an instance of the Element in memory and test the porperty

if (!!document.createElement('element').property) {...}

// Example (from MDN):
function supports_canvas() {
return !!document.createElement('canvas').getContext;
}

if(supports_canvas()) { ... }

Remidner: !! returns the truthy value (bool).

→ MDN

CSS Feature support

equivalent of CSS’s @supports(property: value).

CSS.supports("property", "value")

→ MDN

Media Query

equivalent of CSS’s @media

window.matchMedia('(max-width: 600px)');

check match with .matches (bool):

const mq = window.matchMedia('(max-width: 600px)');

// Checking for matches:
if (mq.matches) {
  // media query matches!
}

// Listening for matches:
mq.addEventListener('change', e => {
  if (e.matches) {
    // ...
  }
});

Careful: At the time of writing the addEventListener example does not work in Safari and IE, see browser compatibility table (MDN).

→ MDN, in depth: CSS Ttricks