I have a style.css with a media query. In my javascript-file, I have a value for the desired mobile-width stored in a variable.
By changing the variable, I want to change the value of the media query automatically. Is it somehow possible to alter the contents of the .css-file with javascript like I can change the DOM?
Adding a HTML <style>
-element to the DOM using javascript is not my desired solution, because I want to keep all css in the .css-file
Using Media Queries With JavaScriptMedia queries was introduced in CSS3, and is one of the key ingredients for responsive web design. Media queries are used to determine the width and height of a viewport to make web pages look good on all devices (desktops, laptops, tablets, phones, etc).
}); 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.
Media queries are commonly associated with CSS, but they can be used in HTML and JavaScript as well.
Yes, you may use media queries in a <style> tag. The image is only loaded if the CSS requires it to be, so if nothing matches the selector then it won't bother loading the image.
You can set the rule directly using .media.mediaText
of document.styleSheets[0].cssRules
document.styleSheets[0].cssRules[0].media.mediaText = /* new media rule here */;
plnkr http://plnkr.co/edit/qzLO5J4KlWZLQnjMIy7i?p=preview
The best option would be to have two sets of media queries which are only applied based on a parent class being present.
@media (max-width: 600px) {
.w600 .myDiv{
color:red;
}
}
@media (max-width: 400px) {
.w400 .myDiv{
color:red;
}
}
You could then add/remove w600
or w400
to the body
class to allow the required media query to work.
Using jQuery this could be done like:
$("body").addClass("w600")
.removeClass("w400");
I appreciate you may have more than just one style and would therefore like to reduce code duplication.
In which case you could use a CSS transpiler such as Less with mixins:
@mediaqueryruleset:{
.myDiv{
color:red;
}
.myOtherDiv{
color:blue;
}
}
@media (max-width: 600px) {
.w600 {
@mediaqueryruleset();
}
}
@media (max-width: 400px) {
.w400 {
@mediaqueryruleset();
}
}
Which would output:
@media (max-width: 600px) {
.w600 .myDiv {
color: red;
}
.w600 .myOtherDiv {
color: blue;
}
}
@media (max-width: 400px) {
.w400 .myDiv {
color: red;
}
.w400 .myOtherDiv {
color: blue;
}
}
You can write by using $(window).width()
value=959;
if($(window).width() < value)
{
$(".classname").css("color","white");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With