SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Addict
    Join Date
    Sep 2008
    Posts
    341
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Detect browser/screen width

    In addition to media queries with CSS I want JavaScript to also perform some actions based on screen/browser width.

    As an example, when the browser is extended greater than 1400px as well as media queries showing more options in the top navigation bar, I would like JavaScript to perform an Ajax request to get additional data. This is just an example, but I want to do various things like this.

    I only need to know a cross-browser and reliable way to detect the browser width so JS returns exactly the same value as media queries does?

    This should detect it correctly on desktops, laptop, tablets and mobiles.

  2. #2
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,117
    Mentioned
    152 Post(s)
    Tagged
    0 Thread(s)
    I believe in jQuery you can perform $(window).width()

    And you can attach an event to resize(), so it runs when the user resizes their browser window
    Code JavaScript:
    $(function()
    {
      $(window).bind('resize', function()
        {
           // grab the width
           var width = $(this).width();
        }
      );
    });

    Granted, you will need to run this function on DOM load too, as the resize event is only called when the window size changes.

  3. #3
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,117
    Mentioned
    152 Post(s)
    Tagged
    0 Thread(s)
    Just remembered, you might also have success with document.documentElement.clientWidth and/or document.body.clientWidth

  4. #4
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,799
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    Different browsers track the viewport width in different fields. The following is the shortest code that will get the value from whichever of the three places that the browser uses.

    Code:
    var viewportWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •