I have a style.css with a media query. In my javascript-file, I have a value for the desired mobile-width stored in a variable.
By changing the variable, I want to c
Yes. Maybe. Inspired by @guest271314 answer. This seems to allow the changing of the media query conditions via JavaScript.
document.styleSheets[0].cssRules[0].conditionText = "(min-width: 0px)";
Of course, check if the rule has media query applied:
var currentQuery = {index:0,rule:null,mediaText:null};
var inclusionQuery = "(min-width: 0px)";
var exclusionQuery = "(min-width: 99999px)";
var numberOfMediaQueries = 0;
function hideAllMediaQueries() {
var rules = document.styleSheets[0].cssRules;
var firstQueryIndex = 0; // show this query
var queryIndex = 0;
var numberOfRules = rules!=null ? rules.length : 0;
// loop through rules and hide media queries except selected
for (var i=0;i<numberOfRules;i++) {
var rule = rules[i];
if (rule.media!=null) {
if (queryIndex==firstQueryIndex) {
currentQuery.mediaText = rule.conditionText;
currentQuery.index = firstQueryIndex;
currentQuery.rule = rule;
rule.conditionText = inclusionQuery;
}
else {
rule.conditionText = exclusionQuery;
}
queryIndex++;
}
}
numberOfMediaQueries = queryIndex;
}
Note: The example above only applies to existing media queries in your CSS. It does not add or remove queries. It checks if media query exists by checking that the rule.media
property is not null.