Skip to content

Instantly share code, notes, and snippets.

@rutger1140
Created April 12, 2012 10:03
Show Gist options
  • Save rutger1140/2366187 to your computer and use it in GitHub Desktop.
Save rutger1140/2366187 to your computer and use it in GitHub Desktop.
Display viewport width with jQuery
/**
* Display your window width - useful for responsive web design
* @author: Rutger Laurman
*/
// Ready?
$(function(){
// Create debug element
$("body").append("<div style='position:fixed;top:0;left:0;border:1px solid #999;background:#eee;' id='viewportwidth'></div>");
// Set contents on resizing window
$(window).resize(function(){$("#viewportwidth").html($(window).width());});
// Trigger resize event
$(window).resize();
});
@rutger1140
Copy link
Author

Bookmarklet of this gist: https://gist.github.com/3060429

@joshcoast
Copy link

I came up with a very simmular solution, but when I actually mesure the width of the window, it's wrong. For example, I have a media query as such, @media only screen and (min-width: 768px), when I resize the window to hit the media query at 768px, the $(window).width() is reporting 699px. I even measured it with a screen measuring app and the css media query is spot on, but the js is reporting a short number. Any idea why this would be?

@rutger1140
Copy link
Author

@joshintosh Maybe it has something to do with browserbars or the padding on your html or body tag. Does it do the same with other websites?

Also this snippet evolved into this: https://gist.github.com/lekkerduidelijk/3060429

Do check out @roelven his version, it's more stable than mine: https://gist.github.com/lekkerduidelijk/3060429#comment-757435

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment