-
-
Save mindplay-dk/52883a8b70289baa7ec89b4a21b0c0e2 to your computer and use it in GitHub Desktop.
Responsive classes (for modern browsers, in Typescript)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Responsive { | |
private _breakpoints: { width: number, name: string }[] = [] | |
private _targets: { () : Element }[] = [] | |
private _source: Window | |
constructor(source: Window) { | |
source.addEventListener("resize", () => { this._update() }) | |
} | |
/// Define class-name for horizontal breakpoint | |
at(width: number, name: string) : this { | |
this._breakpoints.push({ width, name }) | |
this._breakpoints.sort((a, b) => a.width - b.width) | |
return this | |
} | |
/// Define class-name beyond the last horizontal breakpoint | |
atHigher(name: string) : this { | |
return this.at(999999, name) | |
} | |
/// Apply class-name to a given target element (defaults to body) | |
update(target: HTMLElement | string = document.body) : this { | |
this._targets.push( | |
target instanceof HTMLElement | |
? () => target | |
: () => document.querySelector(target) | |
) | |
this._update() | |
return this | |
} | |
private _update() { | |
var width = window.innerWidth | |
var active = this._breakpoints.filter(bp => width <= bp.width).shift().name | |
console.log(width, active) | |
this._targets.forEach(target => { | |
this._breakpoints.forEach(bp => { | |
target().classList.toggle(bp.name, bp.name === active) | |
}) | |
}) | |
} | |
} | |
new Responsive(window) | |
.at(480, "m320") | |
.at(740, "m768") | |
.at(971, "tablet") | |
.atHigher("desktop") | |
.update(document.body) | |
new Responsive(window) | |
.at(650, "mobile-menu") | |
.atHigher("desktop-menu") | |
.update("body") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment