npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

screen-size-detector

v1.0.4

Published

A small utility to detect screen (viewport) size (resolution height and width) and listener to resize event with additional features

Downloads

1,883

Readme

screen-size-detector

screen-size-detector

Table of Contents

Introduction

screen-size-detector is a small utility to detect screen (viewport) size (resolution height and width) and listener to resize event with additional features. You may think of it as some sort of JavaScript media query (among other things) in at its core.

Features

  • Easy current screen width and height getters. For example: screen.width and screen.height

  • Predefined screen width detections, for example screen.is.mobile, screen.is.laptop, etc.

  • You may specify callback (functions) to be triggered on screen width change, screen height change and screen width and height change (3 different callbacks support)

  • You may overwrite the predefined screen width configurations, and you may add your own screen width definitions and configurations, at instance creation or at any time by using the available methods, as much as you want

  • You may set and/or remove 3 different callbacks (all optional) to be executed for when the current screen width:

    • enters
    • is inside
    • leaves

    the defined screen width range (min and max), of any defined screen width

  • You can specify a (function) callback to be executed after the usage completion of all available methods:

    • setMainCallback
    • removeMainCallback
    • addWidthDefinitions
    • removeWidthDefinition
    • setWidthCategoryCallback
    • removeWidthCategoryCallback
  • You may modify the configurations and definitions of the instance at any time after initialisation

  • No external dependencies and lightweight

Install

Using NPM:

npm install --save screen-size-detector

Using Yarn:

yarn add screen-size-detector

In browser:

Using CDN:

<script src="https://unpkg.com/screen-size-detector@latest/dist/screen-size-detector.min.js"></script>

Using local file:

<script src="./dist/screen-size-detector.min.js"></script>

Usage

The most basic usage example (In Node.js):

const ScreenSizeDetector = require('screen-size-detector');
// or
//import ScreenSizeDetector from 'screen-size-detector';

const screen = new ScreenSizeDetector(); // Default options
console.log(screen.width); // Then use screen anywhere in your project

The most basic usage example (In browser):

<script src="https://unpkg.com/screen-size-detector@latest/dist/screen-size-detector.min.js"></script>

<script>
const screen = new ScreenSizeDetector(); // Default options
console.log(screen.width); // Then use screen anywhere in your project   
</script>

Initialisation

As shown above, to use screen-size-detector, you just have to initialise an instance, with an optional argument of options object:

const screen = new ScreenSizeDetector(/*options object goes here. Optional.*/);

Options

The default options used if no options is supplied are as follows:

const defaultOptions = {
  onHeightChange: () => {}, // OPTIONAL: A callback to trigger on screen height change
  onWidthChange: () => {}, // OPTIONAL: A callback to trigger on screen width change
  onBothChange: () => {}, // OPTIONAL: A callback to trigger on screen width and height change
  widthDefinitions: { // Width definitions object. Can be overwritten, added or removed
    smartwatch: {
      min: 0,
      max: 319,
      inclusion: "[]",
    }, 
    mobile: {
      min: 320,
      max: 480,
      inclusion: "[]",
    },
    tablet: { // Width category name. Will appear on <instance>.is.<width category name> Ex: screen.is.tablet which will return true or false
      min: 481, // Minimum screen width in pixel for this category
      max: 768, // Maximum screen width in pixel for this category 
      inclusion: "[]", // "inclusion" will only accept the combination of either '[]', '[)', '(]' or '()'. '[' means include the min value, '(' means exclude the min value, ']' means include the max value and ')' means exclude the max value.
        
        /* For the example of this 'tablet' category, this is what it means for the inclusion:
        	If '[]' is provided: Range for smartwatch is defined is 481 px - 768 px
        	If '[)' is provided: Range for smartwatch is defined is 481 px - 767 px
        	If '(]' is provided: Range for smartwatch is defined is 480 px - 768 px
        	If '()' is provided: Range for smartwatch is defined is 480 px - 767 px
        */
        onEnter: () => {}, // OPTIONAL: A callback that will be triggered once screen width enters this width range (481px - 768px)
        whileInside: () => {}, // OPTIONAL: A callback that will be triggered while screen width changes within this width range (481px - 768px)
        onLeave: () => {}, // OPTIONAL: A callback that will be triggered once screen width leaves this range (481px - 768px)
    },
    laptop: {
      min: 769,
      max: 1024,
      inclusion: "[]",
    },
    desktop: {
      min: 1025,
      max: 1200,
      inclusion: "[]",
    },
    largedesktop: {
      min: 1201,
      max: Infinity,
      inclusion: "[]",
    },
  },
};

// Use it like so:
const screen = new ScreenSizeDetector(defaultOptions); // same as const screen = new ScreenSizeDetector(); since the above are the default options.

Properties

  • width

    • Description: The current width of the screen in pixels

    • Example:

    • console.log(`The current screen width is ${screen.width}`);
  • height

    • Description: The current height of the screen in pixels

    • Example:

    • console.log(`The current screen height is ${screen.height}`);
  • is.<widthCategoryName>

    • Description: A boolean of whether the current screen width is within the specified widthCategoryName configuration inside the widthDefinitions option

    • Example:

    • console.log(`The current screen width is in mobile category: ${screen.is.mobile}`);

Methods

Here are the available methods on the initialised object:

  • setMainCallback (when, callback[, onDone])

    • Description: A method to set callback to be executed. Available events are on width change, height change and both width and height change

    • when | When to trigger the callback. The options are widthchange, heightchange and bothchange (required)

    • callback | The callback to be triggered when the condition is met (required)

    • onDone | A callback (optional)

    • Example:

    • const input = document.querySelector('input');
      input.value = screen.width;
      screen.setMainCallback('widthchange', () => input.value = screen.width); // Reactive
  • removeMainCallback (widthCategoryName, when[, onDone])

    • Description: A method to remove callback for events of width change, height change or both width and height change

    • when | The event where the callback to be removed. The options are widthchange, heightchange and bothchange (required)

    • onDone | A callback (optional)

    • Example:

    • const onDone = () => {
          console.log ('Done removing width change callback');
      }
          
      screen.removeMainCallback('widthchange', onDone);
  • addWidthDefinitions (widthDefinitionObject[, onDone])

    • Description: A method to add width definition to the instance

    • widthDefinitionObject | Width definition object, the structure is the same as Options (defaultOptions) object above (required)

    • onDone | A callback (optional)

    • Example:

    • const widthDefinitionObject = {
          laptopandsmaller: {
            min: 0,
            max: 1024,
            inclusion: "[]",
          },
          largerthanlaptops: {
            min: 1025,
            max: Infinity,
            inclusion: "[]",
          },
      };
          
      const onDone = () => {
          console.log(`Done adding. Is my screen width laptop and smaller: ${screen.is.laptopandsmaller}`);
      };
          
      screen.addWidthDefinitions(widthDefinitionObject, onDone);
  • removeWidthDefinition (widthCategoryName[, onDone])

    • Description: A method to remove width definition from the instance

    • widthCategoryName | Width category name (required)

    • onDone | A callback (optional)

    • Example:

    • const onDone = () => {
          console.log(`Done removing. My current screen width is: ${screen.width}px`);
      };
          
      screen.removeWidthDefinition('smartwatch', onDone);
  • setWidthCategoryCallback (widthCategoryName, when, callback[, onDone])

    • Description: A method to set the callback to be triggered whether the width range has been entered, is inside or exited

    • widthCategoryName | Width category name (required)

    • when | When to trigger the callback. The options are enter, whenInside and leave (required)

    • callback | The callback to be triggered when the condition is met (required)

    • onDone | A callback (optional)

    • Example:

    • const applyMobileClass = () => {
          const listItems = document.querySelectorAll(".main-container li");
          const mobileClass = 'in-mobile';
          
          listItems.forEach(el => {
              el.classList.add(mobileClass);
          });
      }
        
      const removeMobileClass = () => {
          const listItems = document.querySelectorAll(".main-container li");
          const mobileClass = 'in-mobile';
          
          listItems.forEach(el => {
              el.classList.remove(mobileClass);
          });
      }
          
      const onDone = () => {
          console.log ('Done setting callback');
      }
          
      screen.setWidthCategoryCallback('mobile', 'enter', applyMobileClass, onDone);
      screen.setWidthCategoryCallback('mobile', 'leave', removeMobileClass, onDone);
  • removeWidthCategoryCallback (widthCategoryName, when[, onDone])

    • Description: A method to remove width category callback from the instance

    • widthCategoryName | Width category name (required)

    • when | The event where the callback to be removed. The options are enter, whenInside and leave (required)

    • onDone | A callback (optional)

    • Example:

    • const onDone = () => {
          console.log ('Done removing mobile enter callback');
      }
          
      screen.removeWidthCategoryCallback('mobile', 'enter', onDone);

Issues, Questions and Suggestions

Have any issues, questions or suggestions? You are very welcomed to head over to the Issues page and let's see what we can do together to make this small utility better

License

MIT