19

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.

3
  • 1
    Just updating an existing style element's contents seems to work fine: jsfiddle.net/vfLS3 Commented Apr 17, 2013 at 3:35
  • Do you mean adding a css media query rule? Commented Apr 17, 2013 at 3:39
  • @ExplosionPills That is perfect and a worthy 'answer' Commented Apr 17, 2013 at 3:46

4 Answers 4

35

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/

Sign up to request clarification or add additional context in comments.

5 Comments

$('style').text("@media (min-width:400px) {div{ color:red; }}")
@MuhammadUmer that would overwrite the entire contents of the style element rather than append to it
@MuhammadUmer .append does not append text content but rather an element. If the argument is a string, jQuery will attempt to select the element and will choke on @
but it does add text also
but safer way to do it would be like this $('p')[0].innerHTML='css';
7

I use this way. This allows to update multiply styles in document

in HTML:

<style class="background_image_styles">
</style>

in JS

$(".background_image_styles").text("@media (min-width: 1200px) {.user_background_image{background-image: url('https://placehold.it/1200x300');}}");

Comments

2

For general purpose use, you can append a style sheet to document.head. Then you can put any mods in there you want -- including media queries. Since it's the final style sheet in document.head, it overrides any prior CSS rules.

Vanilla JavaScript:

    let style = document.getElementById('custom-styles');
    if (!style) {
      style = document.createElement('style');
      style.id = "custom-styles";
      document.head.appendChild(style);
    }
    style.innerHTML =
      "@media screen and (min-width:400px) {...}";

Comments

0

I prefer this variant - appending to the end of the head section:

$('<style/>', {
    text: '@media print { @page { margin: 10 20 20 10; } body { margin: 0.5cm; }}',
    appendTo: win.document.head
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.