Foundation 5 – Execute Javascript/jQuery on breakpoint changed

I am working on a Foundation 5 website and i would like to detect the breakpoint change when the user resize the browser window. Here is a workaround found in the Foundation Forum.

1. Add the following piece of HTML to your website. Since i am working with Drupal 7 with the Foundaiton 5 theme, i just add it to the page.tpl.php in the subtheme.

<!-- For breakpoints checking in js -->
<div id="breakpoints"> 
  <div class="breakpoint-small show-for-small-only" data-size="small"></div>
  <div class="breakpoint-medium show-for-medium-only" data-size="medium"></div>
  <div class="breakpoint-large show-for-large-only" data-size="large"></div>
</div>

 

2. Hide the above HTML in the styling sheets. Here is the SASS code.

#breakpoints {
  height:0px;

  div {
    width:1px;
    height:0px;
    visibility:hidden;
  }
}

 

3. In the Javascript file, implement the $(window).resize() as follow.

// Breakpoints checking in js
var breakpoint = $('#breakpoints div:visible').first().data('size');
var resizeTimeoutId;

$(window).resize(function() {
  clearTimeout(resizeTimeoutId);
  resizeTimeoutId = setTimeout(function() {
    breakpoint = $('#breakpoints div:visible').first().data('size');
    console.log(breakpoint); // For debug
    switch (breakpoint) {
      case 'small':
        // Codes when resize to small screen
        break;
      case 'medium':
        // Codes when resize to medium screen
        break;
      case 'large':
        // Codes when resize to large screen
        break;
      default:
        break;
    }
  }, 250); // The delay time in ms for the action to take place after resize.  
});

 

Done =)

Reference: Foundation Forum – Determine screen-size media query using Javascript

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.