【Javascript】matchMedia / addEventListener【レスポンシブ】
《参考》
matchMedia / MediaQueryList / addEventListener
https://developer.mozilla.org/ja/docs/Web/API/Window/matchMedia
https://developer.mozilla.org/ja/docs/Web/API/MediaQueryList
https://developer.mozilla.org/ja/docs/Web/API/EventTarget/addEventListener
https://github.com/mdn/dom-examples/blob/master/mediaquerylist/index.html
JavaScript
var mql = window.matchMedia('(max-width: 767.98px)');
function screenTest(e) {
if (e.matches) {
// max-width: 767.98pxの時
// ここに記述
} else {
// そうでない時 = min-width:768pxともいう
// ここに記述
}
}
screenTest(mql);
mql.addEventListener('change', screenTest, false);
レスポンシブコーディングをする際は必須といえるかなと思います。
var mql = window.matchMedia('(max-width: 767.98px)');
function screenTest(e) {
if (e.matches) {
// max-width: 767.98pxの時
window.addEventListener('DOMContentLoaded', () => {
// ここに実行したい処理を書くとか
});
} else {
// そうでない時 = min-width:768pxともいう
// 具体的に例えば100pxスクロールしたらheaderにクラス名付与するとか
window.addEventListener("scroll", function () {
const header = document.querySelector("header");
header.classList.toggle("header-fixed", window.scrollY > 100);
});
}
}
screenTest(mql);
mql.addEventListener('change', screenTest, false);
ちょっとした具体例でした。