Use Javascript or JQuery to insert a responsive CSS rule
Suppose I want to dynamically add CSS rules tied to a media condition. For example, something like the following:
@media only screen and (min-device-width : 500px){
.someClass: {
color: blue;
}
}
The logical step would be to use JavaScript to validate the media query and insert a rule if the test passes. Something like the following:
if(matchMedia(only screen and (min-device-width : 500px))){
$('.someClass').css('color', 'blue');
}
The downside is that the rule will NOT react. If I resize the screen the blue color does not change accordingly. I can add a listener to the screen resize, but I think this is a bit overkill.
My question is, is there a way to add a response rule via Javascript or JQuery?
source to share
You want to hear about enquire.js :
enquire.register("screen and (max-width:1000px)", {
match : function() {}, // REQUIRED
// Triggered when the media query transitions
// *from an unmatched state to a matched state*
unmatch : function() {}, // OPTIONAL
// If supplied, triggered when the media query transitions
// *from a matched state to an unmatched state*.
setup : function() {}, // OPTIONAL
// If supplied, a one-time setup function
// triggered when the handler is first registered.
deferSetup : true, // OPTIONAL, defaults to false
// If set to true, defers execution the setup function until
// the media query is first matched. Setup is still triggered just once.
destroy : function() {} //OPTIONAL
// If supplied, triggered when a hander is unregistered (covered later).
// Enables you to provide lifecycle to responsive widgets.
// Put cleanup logic here.
}).listen(); // More on this next
[from docs]
EDIT: If you want to add a pure CSS rule via js [without relying on a listener] I think this is not possible.
source to share
You can render dynamic css using responsive.js library. This will help you define dynamically your flex rules, which will render on the client side as native css. It uses a fluent interface programming style and it works also if media query support isn't supported (dynamically display the current rules in effect).
For example, you can define the width property as:
r$.breakpoints(320,767,1280);
r$.set('width','px').values(100,300,1500).linearInt().applyTo('.class');
More information, downloads and examples at:
source to share