media-trigger
v4.3.0
Published
MediaTrigger is designed to control the response to changes in media queries, allowing you to perform specific actions when entering or exiting a particular media state, or any change to a media state.
Maintainers
Readme
0.5kB gzipped
Demo
➤ Install
$ yarn add media-trigger➤ Import
import MediaTrigger from 'media-trigger';➤ Usage
const mediaTrigger = new MediaTrigger({
media: '(min-width: 992px)',
entry: (mq) => {
console.log('Entered media query:', mq.media);
},
exit: (mq) => {
console.log('Exited media query:', mq.media);
},
change: (mq) => {
console.log('Media query change:', mq.media, 'matches:', mq.matches);
}
});
mediaTrigger.init();➤ Options
| Option | Type | Default | Description |
|:--------:|:--------------------:|:----------:|:-------------------------------------------------------------------------------------------|
| media | string | Required | The media query string to be observed. |
| entry | function | null | null | Callback function invoked when the media query starts matching (matches becomes true). |
| exit | function | null | null | Callback function invoked when the media query stops matching (matches becomes false). |
| change | function | null | null | Callback function invoked on any change in the media query's matching state. |
➤ Methods
| Method | Description |
|:------------|:-------------------------------------------------------------------------------|
| init() | Initializes the media query listener and triggers the initial state callbacks. |
| destroy() | Removes the media query listener to stop observing changes. |
➤ Example
// Initialize a MediaTrigger instance
const mediaTrigger = new MediaTrigger({
media: '(max-width: 768px)',
entry: (mq) => {
console.log('Screen is now less than or equal to 768px wide.');
},
exit: (mq) => {
console.log('Screen is now wider than 768px.');
}
});
// Start listening to media query changes
mediaTrigger.init();
// Later, if you want to stop listening
mediaTrigger.destroy();➤ Browser Support
MediaTrigger relies on the window.matchMedia API, which is supported in all modern browsers. If window.matchMedia is not available, MediaTrigger will safely do nothing.
➤ License
media-trigger is released under MIT license
