Search code examples
javascriptcssmedia-queries

Media queries JavaScript also on browser working


I was trying something with JavaScript and media queries. I want to change some elements with JavaScript, like switching elements etc.

When the browser/device width is 320px I want to do something.

I came up with the following, but this doesn't work:

if (screen.width < 320){ 
    $('input[type="text"]').insertAfter('label');
    $('input[type="text"]').eq(1).remove();
    $('input[type="text"]').eq(2).remove();             
}

What am I doing wrong?

When I would like to do this for some changes of my CSS it looks like this:

@media only screen and (max-width : 400px) { }

And the example above I want to convert to JavaScript.


Solution

  • Yes. You can do so by using $(window).width().

    if ($(window).width() < 320) {    
      $('input[type="text"]').insertAfter('label');
      $('input[type="text"]').eq(1).remove();
      $('input[type="text"]').eq(2).remove();
    }
    

    Also, if you want to check if a resize has happened without refreshing, use $(window).resize().

    Here's an example jsFiddle of resize in use.