treehouse : what would you like to learn today?
Web Design Web Development iOS Development

jquery window width condition

  • Hi!
    I have this code :
      if ( $(window).width() > 800 ) {
    $("#header").hide();

    $("#header").find("a").on("click", function() {
    $(this).parents("#header").fadeOut("slow");
    return $(this).hasClass('close') ? false : true;
    });

    $("a#toggle").click(function() {
    $("#header").fadeToggle("slow", "linear");
    });
    }

    I think I miss something because when the window is smaller than 800 the #header is still hidden so I think I need to add an 'else' condition or something.
    And also how can I add a bunch of css code only when the windows is bigger than 800 or it's better to use css media queries ?
    Thanks
  • I'd definitely use media queries here, and not the jQuery route, if you just want to hide it when screens are less than 800 wide.

    Something like this:

    @media only screen and (max-device-width: 800px) {
    #header {display:none;}
    }
  • I can not use only media queries, because i have this
    $("#header").find("a").on("click", function() {
    $(this).parents("#header").fadeOut("slow");
    return $(this).hasClass('close') ? false : true;
    });

    $("a#toggle").click(function() {
    $("#header").fadeToggle("slow", "linear");
    });

    which I want to execute only when the window is bigger than 1200
  • I've tried this and it's not working proper:
    $(document).ready(function() {
    if ( $(window).width() > 800 ) {
    $("#header").hide();
    }
    else {
    $("#header").show();
    }

    });

    f I resize the window below 800 the header is still invisible. What is the problem ? I can't use css media queries because I want to execute other functions when the windows is bigger than 800.
  • The problem is your above code only runs on DOM ready, so it only runs once. You need to run the above code each time the window is resized.

    Also, Senff is right, I highly suggest you find a way to do this with media queries rather.
  • I know it's better with media queries but the problem is that I want to display the #header only when a button is clicked only when the browser width is greater than 800px because I do not want to alter the css properties for mobile devices