How to get the width of the HTML document/web page window using JavaScript? (using jQuery library)

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    How to get the width of the HTML document/web page window using JavaScript? (using jQuery library)

    jQuery provides a one-use solution for finding out what the width of the HTML document/web page window is - jQuery focuses on the back-end of making sure it returns the window width regardless of the browser used - whether IE, Opera, Firefox, etc. - while you as a developer only need to use $(window).width() in order to fetch the width of the window.

    In our use case scenario on this forum:

    Code:
    if($(window).width() > 1024) { $('#blog_rss').show(); }
    The width() method returns the current width of the window in pixels. The benefit of checking this is you can hide certain HTML elements on the web page if they overlap on smaller resolutions or when, in Windows 7 and Windows 8, the browser window is snapped causing the width of the window to be small enough causing a certain HTML element to overlap other elements, for example.

    On our forum, we make use of this check to hide the RSS feed floated on the left if a user has a window width that is less than, or equal to, 1024 pixels.

    Obviously, because you're using the jQuery JavaScript library you need to include the jQuery library in your <head> section. You can either host the jQuery library source code locally on your server or through a content delivery network. Whenever you use jQuery, make sure that the document has fully loaded and is ready to be manipulated by jQuery using $(document).ready(). For example:

    Code:
    $(document).ready(
    function(){
     if($(window).width() > 1024) { $('#blog_rss').show(); }
    });
Working...
X