GithubHelp home page GithubHelp logo

dan503 / mq-js Goto Github PK

View Code? Open in Web Editor NEW
6.0 1.0 3.0 4.94 MB

Media queries in JavaScript inspired by the mq-scss Sass mixin

Home Page: https://dan503.github.io/mq-js/

License: MIT License

JavaScript 45.34% TypeScript 7.57% Pug 25.71% SCSS 21.38%
mq-scss javascript media query responsive breakpoints

mq-js's Introduction

Visit the mq-js website

mq-js was inspired by the mq-scss Sass mixin. I wanted to use media queries in JavaScript in a similar sort of way to how I was using media queries in my Sass code.

Full documentation for mq-js can be found at https://dan503.github.io/mq-js/

// MQ-JS

if (mq.inside(600, 1000)) {
   // Functionality for screens between 600px and 1000px
}
// MQ-SCSS

@include mq(inside, 600px, 1000px) {
   // Styles for screens between 600px and 1000px
}

Quick start guide

This documentation assumes that you have the ability to use ES6 JavaScript syntax in your project. mq-js will work in environments that don't support es6 JavaScript syntax however the syntax will be different to what is documented. View the full documentation for ES5 (IE friendly) examples.

If you are new to Node and npm, read this beginners guide on how to get set up. You will also need JavaScript bundling software such as Browserify, Rollup, or Webpack integrated into your build process for mq-js to work.

Once that is all set up, install mq-js using npm.

npm install mq-js --save

Now, create this simple mq.js file to set up your website breakpoints.

///////////////////
// "mq.js" file //
/////////////////

import MQ from 'mq-js'

// Define your Site break points here
const bp = {
   small: 600,
   medium: 980,
   large: 1200,
}

// Creates the media query functions
const mq = new MQ(bp)

// Export mq by default
export default mq

// Gives easy access to your site breakpoints
export { mq, bp }

Now import the mq variable into your main/component JavaScript file.

////////////////////////
// Component js file //
//////////////////////

// Import the mq variable that was created in the setup stage
import mq from '../mq'

// Alternatively import both the mq variable and the website breakpoints
// (Use one line or the other, do not use both import statements)
import { mq, bp } from '../mq'

document.querySelector('#button').onclick = function (e) {
   e.preventDefault()

   // Use your breakpoints by parsing in a string
   mq.min('medium', (screen_size) => {
      this.classList.toggle('-active')

      // Log the screen height, width and ratio at the time the button was clicked
      console.log(screen_size)
   })

   // Alternatively, use it in an if statement
   if (mq.max('small')) {
      // Do stuff for screens that are up to (and including) the "small" breakpoint width
   }

   // You can also use custom values
   if (mq.min(1000)) {
      // Do stuff for screens that are greater than 1000px wide
   }

   // If you imported the breakpoints, you can use tweaked versions of them
   if (mq.inside(bp.small + 50, bp.medium - 100)) {
      // Do stuff for screens that are between the "small" breakpoint + 50px
      // and the "medium" breakpoint - 100px
   }
}

Note: mq.max is inclusive of the given screen size and mq.min is exclusive of the given screen size. This is to avoid any potential 1px overlap issues where both statements return true at the same time. It is also designed to align with how mq-scss works.

It is also worth noting that you can save your breakpoints into a json file and import that instead. This can make the breakpoints a bit more portable.

{
   "//": "breakpoints.json file",
   "small": 600,
   "medium": 980,
   "large": 1200
}
///////////////////
// "mq.js" file //
/////////////////

import MQ from 'mq-js'

// Retrieve your site break points
import bp from './breakpoints.json'

const mq = new MQ(bp)

// Export mq by default
export default mq

// Easier access to your site breakpoints
export { mq, bp }

Core methods

Note: You can add Width to the end of any of those methods and it will still be valid. For example, it is safe to use mq.minWidth instead of mq.min. The mq.minWidth method has identical functionality to mq.min.

Plugins

Height plugin

import 'mq-js/plugins/height'

The height plugin provides these methods:

  • mq.minHeight
  • mq.maxHeight
  • mq.insideHeight
  • mq.outsideHeight

Read the full height plugin documentation.

Orientation plugin

import 'mq-js/plugins/orientation'

The orientation plugin provides these methods:

  • mq.orientation

Read the full orientation plugin documentation.

Ratio plugin

import 'mq-js/plugins/ratio'

The ratio plugin provides these methods:

  • mq.ratio
  • mq.minRatio
  • mq.maxRatio
  • mq.insideRatio
  • mq.outsideRatio

Read the full ratio plugin documentation.

reactTo plugin

import 'mq-js/plugins/reactTo'

This gives you access to:

  • mq.reactTo

This plugin is a bit different. The primary purpose of this plugin is to fire off a function when a media query either enters or leaves a defined screen size range.

It takes a function that returns an mq-js screen-check result as it's first parameter and a callback function as it's second parameter. It will then call the callback function every time the screen-check result changes from true to false or false to true.

mq.reactTo(
   () => mq.inside(800, 1000),
   (is_active, screen_size) => {
      // is_active = did "mq.inside(800, 1000)" return true?
      // screen_size = an object holding the screen height, width,
      //   and ratio (ratio in both string and number format) at the
      //   point when the screen crossed an mq boundary
      console.log(is_active, screen_size)
   }
)

See a reactTo plugin demo in the full documentation.

The mq-js change log is available on the mq-js GitHub releases page

mq-js's People

Contributors

dan503 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

mq-js's Issues

mq-js not properly compatible with mq-scss when em conversion is turned on

If someone is using mq-scss in em conversion mode and the website user increases their default browser font size, mq-scss and mq-js will get out of sync with one another.

mq-js has no em conversion functionality so the only way around this is to turn off em conversion in mq-scss at the moment.

mq-js needs an em conversion mode. I plan to do this by using window.matchMedia rather than gathering data on the window dimensions and doing the math manually. This is the better way for the plugin to work anyway.

Use Cypress for unit testing

I have a shitty unit testing solution at the moment.

It does the job but using Cypress for this would be immensely better.

Add TypeScript support

The world is moving to TypeScript.

This is still a useful library so it needs to keep up.

I've already made a start on writing out the Types needed for this:

type Callback = (screenSize: number) => void

type SimpleMq<BP> = (bp: keyof BP, cb?: Callback) => boolean
type ComplexMq<BP> = (bp1: keyof BP, bp2: keyof BP, cb?: Callback) => boolean
type ReactToCB = (isActive: boolean, screenSize: number) => void

export interface MqJs<BP extends object> {
	/** Returns `true` if the window size is **less than** the breakpoint size */
	min: SimpleMq<BP>,
	/** Returns `true` if the window size is **greater than** the breakpoint size */
	max: SimpleMq<BP>,
	/** Returns `true` if the window size is **greater than smaller** breakpoint but **less than the larger** breakpoint */
	inside: ComplexMq<BP>,
	/** Returns `true` if the window size is **less than the smaller breakpoint** or **greater than the larger** breakpoint */
	outside: ComplexMq<BP>,
	/** Runs a callback function every time `testMQ` changes from returning `true` to returning `false` */
	reactTo: (testMQ: () => boolean, cb: ReactToCB) => void
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.