cade galt
cade galt

Reputation: 4171

Can I use JavaScript to get the dimensions that media queries use?

For example here is a fiddle which shows how to change a font when the width drops below 200px.

@media (max-width: 200px) {
  .test {
    font-size:40px;
  }
}

If you move the html window to the right to make it smaller you will see the point at which it hits 200px b.c. the font will change.

If someone could add a dynamic div to the fiddle so that this value would be output to the window this would be a cool test script for media queries.

Also, if there is a good reference on the web for the JavaScript interface to media queries. I hope there is one. I have not found it yet.

Upvotes: 0

Views: 68

Answers (3)

user2258887
user2258887

Reputation:

Here is what you were actually asking for. The snippet below will output the dimensions that media query uses.

http://jsfiddle.net/jbnt7nh1/8/

// some code - updated fiddle

Here is a good point to start reading about the different widths in CSS.

https://www.google.com/#q=quirksmode+screen+width

Upvotes: 0

abitcode
abitcode

Reputation: 1582

I did using jQuery, hope this helps.

$( window ).resize(function() {
if($(window).width()<=200){
    $(".test").css("font-size","40px");
}
else{
    $(".test").css("font-size","20px");
} });

http://jsfiddle.net/7gup43rx/2/

Upvotes: 1

andrew
andrew

Reputation: 9583

You can add an event listener to window.matchMedia

if (matchMedia) {
    var mq = window.matchMedia("(max-width: 200px)");
    mq.addListener(WidthChange);
    WidthChange(mq);
}

// media query change
function WidthChange(mq) {

    if (mq.matches) {
        console.log('matches')
    }

}

Demo

Upvotes: 2

Related Questions