Search code examples
javascriptjqueryhtmlcssmedia-queries

is there any down pits with using setTimeout() for jQuery "media query" type situation


I'm working on a responsive site. I'm browsing for a way to handle jQuery "media query" changes so to speak.

I got some calculations like height, width ect on some elements and i would need to recalculate those when the media query change, like from 1160px to 980px.

I found a solution that feels like a good one because it should be supported by most browsers (if not all?) but I'm just not sure if there is any performance or any other issues with having a setTimeout() running as frequent as this one.

jsfiddle for live example

setInterval(function() {
    //code here
}, 100);​

maybe there is some other better way using a already made plugin by paulirish or any other crew? Please advice me with your experience on this subject.


Solution

  • I'm using this code to handle jquery "media queries". I took a element that got the size of my media queries (480, 980, 1160) as selectors, usually a wrapper or like in my case the header.

    var myDivWidth = $('YOUR-SELECTOR').width();
    $(window).resize(function () {
    
        if ($('YOUR-SELECTOR').width() != myDivWidth) {
    
            //If the media query has been triggered
                    myDivWidth = $('YOUR-SELECTOR').width();
    
            //Your resize logic here                
             }
    });