I am wondering if there is a way to use media queries in javascript like i use it in CSS ? i want to handle device-width or orientation and fire a fun
Check out Responsive JavaScript. Sounds like it will do what you're looking for.
Try to use matchMedia (jQuery)
// media query event handler
if (matchMedia) {
var mq = window.matchMedia("(min-width: 500px)");
mq.addListener(WidthChange);
WidthChange(mq);
}
// media query change
function WidthChange(mq) {
if (mq.matches) {
// window width is at least 500px
}
else {
// window width is less than 500px
}
}
I would suggest using window.matchMedia
method , wich allows you to test for a particular media query and add an event listener whenever it's matched or not .
Example :
var mq = window.matchMedia("(max-width: 600px)");
mq.addListener(function(event){
if (event.matches) {
console.log("Small Screen mode !");
}
});
Example 2:
onOrientationChange = function(event){
if (event.matches) {
console.log("Portrait mode!");
}
};
var mq = window.matchMedia("(orientation: portrait)");
mq.addListener(onOrientationChange);
/* ... /*
/* When you no longer need to receive notifications , you can remove the listener */
mq.removeListener(onOrientationChange);
This API is supported in : Chrome 9+ , Firefox 6+ , IE10+
Additional info on MDN