Grow your CSS skills. Land your dream job.

jquery window width condition

  • # June 30, 2012 at 7:34 pm

    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

    # June 30, 2012 at 11:09 pm

    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;}
    }
    # July 1, 2012 at 8:22 am

    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

    # July 1, 2012 at 9:59 am

    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.

    # July 1, 2012 at 11:29 am

    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.

    # July 1, 2012 at 11:57 am

    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

Viewing 6 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".