Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
193
rated 0 times [  200] [ 7]  / answers: 1 / hits: 35956  / 11 Years ago, wed, april 17, 2013, 12:00:00

Is it possible to create full media query rules on the fly using Javascript or jQuery?



I've used numerous media queries to target generalised viewports and specific devices/screens using inline CSS, imports and linked files:



@media screen and (min-width:400px) { ... }
@import url(foo.css) (min-width:400px);
<link rel=stylesheet type=text/css media=screen and (min-width: 400px) href=foo.css />


I can add/remove classes using jQuery:



$(foobar).click(function(){
$(h1,h2,h3).addClass(blue);
$(div).addClass(important);
$('#snafu').removeClass('highlight');
});


I've also look at document.stylesheets and the seemingly archaic and browser-specific:



  document.styleSheets[0].insertRule(p{font-size: 20px;}, 0)


But I can't find any reference to programatically generating:



  @media screen and (min-width:400px)


from javascript directly or in any form.


More From » jquery

 Answers
27

You can just update an existing <style> element (or create one) textContent to contain the rule, which will make it effective in the given context.



document.querySelector('style').textContent +=
@media screen and (min-width:400px) { div { color: red; }}


http://jsfiddle.net/vfLS3/


[#78854] Tuesday, April 16, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
janayr

Total Points: 80
Total Questions: 80
Total Answers: 114

Location: Venezuela
Member since Sat, Aug 22, 2020
4 Years ago
;