Search code examples
javascriptjquerymedia-queriesliquid-layout

Media query on javascript?


I have the following snippet which I want to disable on tablets and mobiles.

if ( !! $('#sidebar').offset()) {    
        var stickyTop = $('#sidebar').offset().top;            
        $(window).scroll(function() {    
            var windowTop = $(window).scrollTop();    
            if (stickyTop < windowTop) {
                $('#sidebar').css({ position: 'fixed', top: "120px" ,  right: "5%" });    
            }
            else {
                $('#sidebar').css('position', 'static');
            }

        });

    }

And I was thinking to wrap in inside a media query or something, like this:

if(@media (min-width:500px)){
if ( !! $('#sidebar').offset()) {

        var stickyTop = $('#sidebar').offset().top;


        $(window).scroll(function() {

            var windowTop = $(window).scrollTop();

            if (stickyTop < windowTop) {
                $('#sidebar').css({ position: 'fixed', top: "120px" ,  right: "5%" });

            }
            else {
                $('#sidebar').css('position', 'static');
            }

        });

    }
}

But I'm sure that this wont work, so how would I stop this code from working on mobiles?


Solution

  • The best solution might be is to style some element differently (even if it's margin:1px) for each media and then detect the computed style. This way, you can use any CSS media rule equally easily and you get full compatibility: CSS:

    #widget{display:none}
    
    @media screen{
      #widget{display:block}
    }
    

    JS:

    if($("#widget").css("display")!="none){
       ...
    }
    

    Note that you should not query the media, but rather browser capabilities because the users of wide tablets (some even have keyboards) might still want to use your sidebar: if(document.width>600){...