Responsive Breakpoint Management with JsWidthBreakpoints Library

Category: Javascript | February 13, 2025
Authormarceloxp
Last UpdateFebruary 13, 2025
LicenseMIT
Views30 views
Responsive Breakpoint Management with JsWidthBreakpoints Library

JsWidthBreakpoints is a handy breakpoint handling library that lets you manage breakpoints with dynamic CSS classes and an optional visual rule.

Features:

  • Dynamic CSS Classes: The core of the library is its automatic application of CSS classes. These classes change as the user resizes their browser window, giving you precise control over your layout at different widths.
  • Visual Rule (Optional): If you want a visual aid, the library can display vertical lines on the screen, marking each breakpoint. This is invaluable during development and testing.
  • Complete Configurability: You’re in control. Set your own breakpoints, customize the rule’s color and opacity, and even choose a prefix for the generated CSS classes.
  • Zero Dependencies: This is pure JavaScript. You don’t need jQuery or any other external libraries.
  • Callback Support: Execute custom code when a breakpoint, this is great for any number of UI tweaks.

The library generates specific CSS classes that correspond to different viewport widths:

  • lt{min-width}: Applied when the window width is less than a breakpoint. (e.g., lt400 for widths below 400px).
  • b{min-width}a{max-width}: Applied when the window width is between two breakpoints. (e.g., b400a600 for widths between 400px and 600px).
  • gt{max-width}: Applied when the window width is greater than a breakpoint. (e.g., gt800 for widths above 800px).

How to use it:

1. Download and load the minified version of the JsWidthBreakpoints library in the document.

<script src="/dist/JsWidthBreakpoints.min.js"></script>

2. Call JsWidthBreakpoints.init() with your desired options.

  • widths (number[]): An array of your breakpoint values (in pixels).
  • applyClasses (boolean): Set to true to enable dynamic CSS class application. Defaults to true.
  • classPrefix (string): The prefix for the generated classes. Defaults to ‘width-‘.
  • rule.show (boolean): Set to true to display the visual rule. Defaults to false.
  • rule.opacity (number): The opacity of the rule lines and labels (0 to 1). Defaults to 1.
  • rule.color (string): The color of the rule lines. Defaults to ‘red’.
  • onBreakPoint (function): A callback function that runs when a breakpoint is reached. It receives an object with oldBreakpoint, currentWidth, and currentBreakpoint properties.
JsWidthBreakpoints.init({
  widths: [320, 640, 760],
  applyClasses: true,
  classPrefix: 'width-',
  rule: {
    show: true, 
    opacity: 0.8, 
    color: 'red', 
  },
  onBreakPoint: (event) => {
    console.log('Breakpoint reached:', event);
  },
});

3. Access Current State:

const currentBreakpoint = JsWidthBreakpoints.currentClass;

You Might Be Interested In:


Leave a Reply