Skip to content

Instantly share code, notes, and snippets.

@mindplay-dk
Last active June 20, 2019 07:22
Show Gist options
  • Save mindplay-dk/52883a8b70289baa7ec89b4a21b0c0e2 to your computer and use it in GitHub Desktop.
Save mindplay-dk/52883a8b70289baa7ec89b4a21b0c0e2 to your computer and use it in GitHub Desktop.
Responsive classes (for modern browsers, in Typescript)
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