Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating CSS media queries with javascript or jQuery

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.

like image 729
nickhar Avatar asked Apr 17 '13 03:04

nickhar


People also ask

Can we use jQuery in media query?

Using this solution, regardless of how the browser treats the scrollbar, the jQuery and CSS media query will fire at exactly the same time. Baring in mind there are various wrappers and solutions that you could use, for something so small this was more than enough.

Can you do media queries in JavaScript?

Flexibility: You can programmatically incorporate media queries into your JavaScript code so that they are only triggered at the onset of a particular event or when certain conditions are met. With a CSS3-only approach, the changes described by a media query go into effect for every screen resize event.

Do media queries go in HTML or CSS?

Using media queries. Media queries are commonly associated with CSS, but they can be used in HTML and JavaScript as well.


2 Answers

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/

like image 75
Explosion Pills Avatar answered Oct 18 '22 12:10

Explosion Pills


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');}}");
like image 22
Server Izetov Avatar answered Oct 18 '22 13:10

Server Izetov