Skip to content

Breakpoint Listener

Creates a listener that triggers actions when the viewport reaches specified breakpoint. This function helps implement responsive behavior dynamically in the application.

Usage

Use getBreakpointListener to respond to changes in screen width, such as adjusting layouts, toggling visibility, or modifying component behavior. Avoid excessive listeners that could impact performance. Combine with clear responsive design patterns to maintain usability across devices.

API Reference

Arguments

ArgumentTypeRequiredDescription
handlerfunctiontrueHandler function that will be called when the breakpoint threshold has been met*. Called immediately after initialization.
breakpointinteger|stringfalseThe desired breakpoint. If a number is given, it will be treated as pixels. By default, it's 768px.
topFramebooleanfalseBy default, the listener measures the current frame. This attaches it to the topmost frame instead, falling back to the current frame when that frame belongs to another origin.

Threshold event

The handler function is invoked only when the window width crosses the specified breakpoint, either becoming narrower or wider, rather than on every resize event. A boolean value is passed as the first argument, indicating the direction of the change.

Returns

Object

PropertyTypeDescription
removefunctionUse this function to remove the event listener when it's no longer needed.

Examples

In plain JS

js
const breakpointListener = Harmonia.getBreakpointListener((matches) => {
  if (matches) {
    console.log('Window is either equal or smaller then the breakpoint');
  } else {
    console.log('Window is bigger then the breakpoint');
  }
}, 1184);

// When no longer needed
breakpointListener.remove();

In a module

js
import { getBreakpointListener } from '@codbex/harmonia';

const breakpointListener = getBreakpointListener((matches) => {
  if (matches) {
    console.log('Window is either equal or smaller then the breakpoint');
  } else {
    console.log('Window is bigger then the breakpoint');
  }
}, 1184);

// When no longer needed
breakpointListener.remove();