Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect Foundation Small/Large Usage in Javascript

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

like image 682
Chris Redford Avatar asked Jul 01 '13 21:07

Chris Redford


2 Answers

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/

like image 127
JustinParker Avatar answered Oct 15 '22 12:10

JustinParker


The default Foundation5 methods handling media queries available are:

// Small queries
Foundation.utils.is_small_only();
Foundation.utils.is_small_up();

// Medium queries
Foundation.utils.is_medium_only();
Foundation.utils.is_medium_up();

// Large queries
Foundation.utils.is_large_only();
Foundation.utils.is_large_up();

// XLarge queries
Foundation.utils.is_xlarge_only();
Foundation.utils.is_xlarge_up();

// XXLarge queries
Foundation.utils.is_xxlarge_only();
Foundation.utils.is_xxlarge_up();

See "Media Queries" under http://foundation.zurb.com/docs/javascript-utilities.html.

like image 31
Samuel Avatar answered Oct 15 '22 10:10

Samuel