Last active
October 28, 2018 16:29
-
-
Save dux/41673bfce1ce6a2f5213b6f253da32c1 to your computer and use it in GitHub Desktop.
Sets media classes to HTML body tag. Example for mobile <body class="mobile not-tablet not-desktop">
This file contains 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
# call just after body tag or $ -> window.MediaBodyClass.init() | |
# sets body class for | |
# mobile to "mobile not-tablet not-desktop" | |
# tablet to "not-mobile tablet not-desktop" | |
# desktop to "not-mobile not-tablet desktop" | |
@MediaBodyClass = | |
sizes: [['mobile'], ['tablet', 767], ['desktop', 1023]] | |
init: -> | |
for [name, size] in @sizes.reverse() | |
if !size || (size && window.innerWidth > size) | |
@set name | |
return | |
set: (name) -> | |
body = $(document.body) | |
for it in @sizes | |
body.removeClass it[0] | |
body.removeClass "not-#{it[0]}" | |
for it in @sizes | |
klass = if it[0] == name then name else "not-#{it[0]}" | |
body.addClass klass | |
# | |
for i in [0..(@MediaBodyClass.sizes.length - 2)] | |
name = @MediaBodyClass.sizes[i][0] | |
[next_name, next_size] = @MediaBodyClass.sizes[i+1] | |
window.matchMedia("(max-width: #{next_size}px)").addListener new Function 'e', | |
"window.MediaBodyClass.set(e.matches ? '#{name}' : '#{next_name}');" |
This file contains 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
this.MediaBodyClass = { | |
sizes: [['mobile'], ['tablet', 767], ['desktop', 1023]], | |
init() { | |
for (let [name, size] of this.sizes.reverse()) { | |
if (!size || (size && (window.innerWidth > size))) { | |
this.set(name); | |
return; | |
} | |
} | |
}, | |
set(name) { | |
const body = $(document.body); | |
for (var it of this.sizes) { | |
body.removeClass(it[0]); | |
body.removeClass(`not-${it[0]}`); | |
} | |
return (() => { | |
const result = []; | |
for (it of this.sizes) { | |
const klass = it[0] === name ? name : `not-${it[0]}`; | |
result.push(body.addClass(klass)); | |
} | |
return result; | |
})(); | |
} | |
}; | |
// | |
for (let i = 0, end = this.MediaBodyClass.sizes.length - 2, asc = 0 <= end; asc ? i <= end : i >= end; asc ? i++ : i--) { | |
const name = this.MediaBodyClass.sizes[i][0]; | |
const [next_name, next_size] = this.MediaBodyClass.sizes[i+1]; | |
window.matchMedia(`(max-width: ${next_size}px)`).addListener(new Function('e', | |
`\window.MediaBodyClass.set(e.matches ? '${name}' : '${next_name}');\` | |
)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment