3

I'm having some issues trying to add media queries with jQuery/javascript. I have a <div class="container"> hidden on small screens with display: none. I want to use the code below to make it show up, although I don't get any errors nothing changes.

$('.container').append('<style type="text/css">@media screen and (min-width: 1012px){ .container { "display": "block"}}</style>');

Any suggestions? Thank you.

4
  • 1
    Why append a media query in JS and not have it in the DOM on load? This is a little redundant and goes against the point of having media queries in the first place. Commented Mar 8, 2016 at 17:43
  • $('head').append.. and you don't need double quotes around display and block Commented Mar 8, 2016 at 17:46
  • Thanks for the info. I know it's much easier to use Media Queries in a CSS style sheet, but in this particular case I have to use JavaScript or jQuery. Commented Mar 9, 2016 at 12:25
  • Does this answer your question? Generating CSS media queries with javascript or jQuery Commented Jun 6, 2022 at 13:32

3 Answers 3

7

It's will work fine if you only delete double quotes form "display": "block"

$('.container').append('<style type="text/css">@media screen and (max-width: 1012px){ .container { display: block}}</style>');

but I think better if you change your selector

$('head').append('<style type="text/css">@media screen and (max-width: 1012px){ .container { display: block}}</style>');
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the info. So far I've tried this, but it doesn't work. Maybe I'm missing something. So basically you append this css style to the head tag?
1

You can use

document.querySelector('style').textContent +=
"@media screen and (min-width: 1012px){ .container { display: 'block'}}"

Get style element and add your new rules, and your html add if no exists

<style>......</style>

Comments

0

The answer of CMedina is quite good, but it appends to the first style element in the document. This could be problematic in two ways:
a) There might not be style element (because <link rel="stylesheet">);
b) There might be more than one style element. Appending style rules to the first one might be overwritten by later ones.

So here's my tactic: create a new <style> element; fill with desired content; append to the body so it comes last

  const styleSheet = document.createElement('style');
  styleSheet.textContent = '@media print { /* ... */ }';
  document.body.appendChild(styleSheet, 'beforeend');

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.