The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Simulating Media Queries in a JS file

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
  • #158708

    Lately I’ve been running into various situations where I need to run bits of Javascript (jQuery) conditionally based on the browsers width. Many times the code will only need to be run when the screen is greater than a certain width. At first, I just wrote a conditional statement like the following:

    $(window).on('resize load orientationchange', function(){
        if ( $(window).width() > 480 ) ) {

    This didn’t seem quite right to me because the resize function runs an absurd amount of times every time you resize your browser, and I have also heard that $(window).width() is inconsistent across browsers.

    Knowing all of this, I have started to use enquire.js. Enquire.js is pretty awesome, but I now find myself struggling with how to set up my functions to mesh well with the “match” / “unmatch” structure of Enquire. You can’t just run a function on match and remove it on unmatch like the $(window).width(). So, I have started to run my functions on match and unbind the events on unmatch. I’ve gotten sufficiently frustrated with this method, so I’m thinking about jumping back to using the $(window).width() method. But this time around, I’m thinking of using it with a throttle or debouncing plugin (so that the window resize event doesn’t fire too often).

    I’m hoping that someone else has tackled this issue and knows of an efficient way of taking care of it. Feel free to let me know if I’ve been doing things all wrong, or you just have some advice. Thanks!


    I don’t know about Enquire. I know Modernizr has a MQ function which you could use.

    Just wanted to say don’t do $(window) inside the event listener. That creates a new jQuery object every time and like you said it gets called a lot. Instead cache that object somewhere like var $window = $(window) and use $window every time you need it.


    Thanks for the tips. The Modernizer MQ seems to be very similar to using $(window).width() although it is probably better because I think there won’t be any discrepancy across browsers. This code will still need to be run on load, resize, and orientation change just as the code I provided above.

    So, I’ll definitely store $(window) as a window next time, but do you also think it would be advantageous to use a throttle or debounce plugin?

Viewing 3 posts - 1 through 3 (of 3 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.