Reputation: 123
How to run this javascript on SP view only.
const navTrigger = document.querySelector('.nav__trigger');
const nav = document.querySelector('nav');
navTrigger.addEventListener('click', event => {
event.preventDefault();
navTrigger.classList.toggle('nav__trigger--active');
nav.classList.toggle('nav--open');
const mediaQuery = window.matchMedia('(min-width: 768px)')
document.body.classList.toggle('overflow'); // THIS CODE
});
Upvotes: 2
Views: 914
Reputation: 1734
// Create a condition that targets viewports at least 768px wide
const mediaQuery = window.matchMedia('(min-width: 768px)')
function handleTabletChange(e) {
// Check if the media query is true
if (e.matches) {
// Then log the following message to the console
console.log('Media Query Matched!')
}
}
// Register event listener
mediaQuery.addListener(handleTabletChange)
// Initial check
handleTabletChange(mediaQuery)
// media query event handler
if(matchMedia) {
const mq = window.matchMedia("(min-width: 500px)");
mq.addListener(WidthChange);
WidthChange(mq);
}
// media query change
function WidthChange(mq) {
if (mq.matches) {
// window width is at least 500px
} else {
// window width is less than 500px
}
}
Upvotes: 1
Reputation: 3589
The matchMedia()
Find out if the screen is less than or greater than 768 pixels wide. And if the condition is met executes the code
const navTrigger = document.querySelector('.nav__trigger');
const nav = document.querySelector('nav');
navTrigger.addEventListener('click', event => {
event.preventDefault();
navTrigger.classList.toggle('nav__trigger--active');
nav.classList.toggle('nav--open');
if (window.matchMedia("(min-width: 768px)").matches) {
document.body.classList.toggle('overflow'); // THIS CODE
}
});
Upvotes: 2