jquery if statement based on screen size

Drhodes picture Drhodes · Sep 13, 2011 · Viewed 34.8k times · Source

I have a slide out nav bar that I would like open by default on screen width of >=1024 and closed by default < 1024. I have a button that toggles it open and closed it. I'm just starting to learn js. I imagine there's a way to set a default toggle state in an if statement if the window width is >=1024. Any help would be greatly appreciated. Here's what I have so far for the toggle.

$('a.expand').toggle(function() {
        $(this).addClass("open");
        $('#nav').animate({width: 50},{queue:false, duration:300});
        $('.wrapify').animate({marginLeft: 50},{queue:false, duration:300});
        $('.primarynav ul').hide();
        $('.navlogo').hide();   

  }, function() {
        $(this).removeClass("open");
        $('#nav').animate({width: 200},{queue:false, duration:300});
        $('.wrapify').animate({marginLeft: 200},{queue:false, duration:300});
        $('.primarynav ul').show();
        $('.navlogo').show(); 

  });

Answer

demux picture demux · Sep 13, 2011
$(document).ready(function() {
    // This will fire when document is ready:
    $(window).resize(function() {
        // This will fire each time the window is resized:
        if($(window).width() >= 1024) {
            // if larger or equal
            $('.element').show();
        } else {
            // if smaller
            $('.element').hide();
        }
    }).resize(); // This will simulate a resize to trigger the initial run.
});

Edit:

Or maybe this is what you're after:

$(document).ready(function() {
    if($(window).width() >= 1024) {
        $('a.expand').click();
    }
});

This will toggle the element when document is ready if the width is correct.