Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding CSS media queries with javascript or jQuery

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.

like image 974
sixtorodriguez Avatar asked Apr 23 '26 10:04

sixtorodriguez


2 Answers

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>');
like image 87
shihab Avatar answered Apr 24 '26 23:04

shihab


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>
like image 45
CMedina Avatar answered Apr 25 '26 00:04

CMedina



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!