Execute Functions Within Certain Breakpoints - jQuery Breakpoints

Execute Functions Within Certain Breakpoints - jQuery Breakpoints
File Size: 10.4 KB
Views Total:
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

The jQuery Breakpoints plugin keeps tracks of breakpoint changes and executes JS functions within certain breakpoints on window resize. Great for responsive web layout to do some cool stuffs depending on the current screen size.

How to use it:

1. Install the jQuery Breakpoints with NPM:

# NPM
$ npm install jquery-breakpoints --save

2. Alternatively you can also download and insert the JavaScript file jquery.breakpoints.min.js into the document.

<script src="https://code.jquery.com/jquery-3.3.1.min.js" 
        integrity="sha384-tsQFqpEReu7ZLhBV2VZlAu7zcOV+rXbYlF2cqB8txI/8aZajjp4Bqd+V6D5IgvKT" 
        crossorigin="anonymous"></script>
<script src="jquery.breakpoints.min.js"></script>

3. Initialize the plugin and we're ready to go.

$(function(){

  $(window).breakpoints();

});

4. Trigger a function when the breakpoint changes.

$(window).bind("breakpoint-change", function(event) {
  console.log(event.from, event.to);
});

$(window).bind("breakpoint-change", function(event) {
  if (event.from === "md") {
    // ...
  }

  if (event.to === "md") {
    // ...
  }
});

5. The pre-defined breakpoints.

$(window).breakpoints({
  breakpoints: [
    {"name": "xs", "width": 0},
    {"name": "sm", "width": 768},
    {"name" : "md", "width": 992},
    {"name" : "lg", "width": 1200}
  ],
});

6. Compare the breakpoints and execute certain functions. Compare methods available:

  • lessThan
  • lessEqualTo
  • greaterThan
  • greaterEqualTo
  • inside
$(window).on('lessThan-md', function() {
  // Do something when viewport is less than 992px
});

7. API methods.

// Returns the current breakpoint name.
$(window).breakpoints("getBreakpoint");

// Returns the current breakpoint width
$(window).breakpoints("getBreakpointWidth");

// Destroys the plugin
$(window).breakpoints("destroy");

8. More plugin options.

$(window).breakpoints({
  
  // A buffer is set before breakpoints trigger breakpoint-change. 
  // The buffer keeps resizing more performant by not triggering actions prematurely.
  buffer: 300,

  // On initializing Breakpoints after the buffer trigger a breakpoint-change so all bindings necessary could happen. 
  // This will return the same event object as regular breakpoint change with event.initalInit.
  triggerOnInit: false,

  // Use $(window).outerWidth() over the default $(window).width() for window width calculations.
  outerWidth: false
  
});

About Author:

Author: Jerry Low

Website: http://jerrylow.com/jquery-breakpoints/


This awesome jQuery plugin is developed by jerrylow. For more Advanced Usages, please check the demo page or visit the official website.