Detect Foundation Small/Large Usage in Javascript

javascript, zurb-foundation

Solution

Yes, you can create a function like this:

var isLarge, isMedium, isSmall;

isSmall = function() {
  return matchMedia(Foundation.media_queries['small']).matches && !matchMedia(Foundation.media_queries.medium).matches;
};

isMedium = function() {
  return matchMedia(Foundation.media_queries['medium']).matches && !matchMedia(Foundation.media_queries.large).matches;
};

isLarge = function() {
  return matchMedia(Foundation.media_queries['large']).matches;
};

Then call it like this:

if (isSmall()) {
  alert("Too small!");
}

if (isLarge()) {
  alert("Too big!");
}

if (isMedium()) {
  alert("Just right!");
}

Another way that is not foundation specific:

In your CSS media query for small only (adjust to suit):

@media only screen and (max-width: 40.063em) {
  body:after {
    content: 'small';
    display: none;
  }
}

In your Javascript, use a function to get the content of that element and compare it:

var getSize;

getSize = function() {
  return window.getComputedStyle(document.body, ':after').getPropertyValue('content');
};

In certain browsers, getSize() will return a value that is quoted, so using if (getSize() == "small") does not work. You can get around that by using this to compare:

if (getSize().indexOf("small") !== -1) {
  // do something
}

Credit to this blog post for this method: http://adactio.com/journal/5429/

Problem

Is there a way to detect whether a Foundation grid is in "small" or "large" mode using Javascript?

Original source