user3305016
user3305016

Reputation: 13

Is it possible to use css like media queries in javascript?

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 function .

now i am using this code :

window.onresize = function(event) {
    /* test for various sizes */
};

but it is no good for me , i don't know how to make it work .

i need it to work in latest chrome without third parity libraries , i'm not sure if it is possible .

Upvotes: 1

Views: 230

Answers (3)

Alexander
Alexander

Reputation: 12785

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

Upvotes: 1

Sunrise
Sunrise

Reputation: 185

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
    }

}

Upvotes: 0

Tyler McGinnis
Tyler McGinnis

Reputation: 35276

Check out Responsive JavaScript. Sounds like it will do what you're looking for.

Upvotes: 0

Related Questions