'JS match.Media with media query range
I am having an issue getting my site to respond to matchMedia query range using media.Match.
Updates based on comments: I need to use match.Media instead of CSS media queries because i need to check if a component is present and if true, i then need to add a class to another element if the browser size is between 1400 - 1800px. Also, i do need this to fire every time the browser is resized.
To troubleshoot, I have tried:
- Using a single matchMedia('(min-width: 1400px) and (max-width: 1800px)')
- Doing a single match (using only min-width: 1400px) and that succeeds. However, when I add in my 2nd variable 'mq.Max' and 'and statement', the whole thing fails.
- I have read through MDN and still not seeing how to implement this.
JS below, thank you for any suggestions you may have.
if (jQuery('.jump-nav').length) {
// Create a condition that targets viewports at least 770px wide
window.onresize = function (event) {
console.log(event);
var mqMin = window.matchMedia('(min-width: 1400px)');
var mqMax = window.matchMedia('(max-width: 1800px)');
// check if media query matches@media (min-width: 30em) and (orientation: landscape)
if (mqMin.matches && mqMax.matches) {
console.log('Media Query Matched!')
// add css class for desktop
$('.rowComponent').addClass('jn-rowchange');
} else {
// remove css class if not desktop
$('.rowComponent').removeClass('jn-rowchange');
}
};
}
Solution 1:[1]
This is something that worked for me!
let mqMin = window.matchMedia("(min-width: 768px)");
let mqMax = window.matchMedia("(max-width: 960px)");
window.onresize = function () {
if (mqMin.matches && mqMax.matches) {
console.log("Inside Query parametara!");
} else {
console.log("Outside Query parametara!");
}
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | user10651574 |