A simple to use javascript library for attaching callbacks to Bootstrap sepecific breakpoints.
The idea is to mimic similiar functionality as found in the Bootstrap SASS mixins.
This library works best with Bootstrap 4 and up after :root
breakpoint variables were added.
1. Include the library via jsDelivr CDN
<script src="https://cdn.jsdelivr.net/gh/thelevicole/[email protected]/dist/breakpoints.js"></script>
2. Initiate library
var bp = new Breakpoints();
3. Start using...
// Set body color to red on 768px and up
bp.up( 'md', function() {
document.body.style.background = '#f00';
} );
// Set body color to green on 768px and down
bp.down( 'md', function() {
document.body.style.background = '#0f0';
} );
Method | Description | Example |
---|---|---|
Attachable | ||
up( name, callback ) |
Attaches a callback to any screen width above the named breakpoint. |
|
down( name, callback ) |
Attaches a callback to any screen width below the named breakpoint. |
|
only( name, callback ) |
Attaches a callback to any screen width within the minimum and maximum widths of the named breakpoint. |
|
between( lower, upper, callback ) |
Attaches a callback to any screen width that spans across the minimum and maximum widths of the two named breakpoints. |
|
Returnable | ||
get( name ) |
Returns a numeric value of the breakpoint. |
|
isUp( name ) |
Returns true if screen width is greater than named breakpoint.
|
|
isDown( name ) |
Returns true if screen width is less than named breakpoint.
|
|
isOnly( name ) |
Returns true if screen width is within the minimum and maximum widths of the named breakpoint.
|
|
isBetween( lower, upper ) |
Returns true if screen width is within the minimum and maximum widths of the two named breakpoints.
|
|
up( name, callback )
var target = document.querySelector( '#example-1 .counter' );
var counter = 0;
bp.up( 'lg', function() {
target.innerText = ++counter;
} );
The above example will count the number of times the callback is called for Large devices and up.
To see it in action just resize your screen...
Large devices (desktops, 992px and up) counter
down( name, callback )
var target = document.querySelector( '#example-2 .counter' );
var counter = 0;
bp.up( 'md', function() {
target.innerText = ++counter;
} );
The above example will count the number of times the callback is called for Medium devices and down.
To see it in action just resize your screen...
Medium devices (tablets, 768px and down) counter
only( name, callback )
var target = document.querySelector( '#example-3 .counter' );
var counter = 0;
bp.only( 'lg', function() {
target.innerText = ++counter;
} );
The above example will count the number of times the callback is called for Large devices and only.
To see it in action just resize your screen...
Large devices (desktops, 992px to 1200px) counter
between( name, callback )