Dynamically adjusted screen dimensions, retina detection and device pixel ratio. When working on website projects that are responsive, it’s imperative to easily know the exact ViewPort dimensions for calculating media query breakpoints. And what comes with responsive design nowadays? Retina and HiDPi displays.
Important: Unless you’re going to run this function alongside jQuery (inside a DOM ready function wrapper), you’ll need to place the script before the closing </body> tag.
Here’s a look at the script, wrapped in an immediately-invoked anonymous function.
First we create the div element which our detection elements will sit inside, there are a series of span classes.
You’ll notice the main function here is the dynamicResizer(), which is present on window.onresize and window.onload. This means the function is executed when the page loads, and is executed when window is beinresized. This is especially great for viewing responsive projects on your smartphone/iPhone/HTC, as the screen width and height is given to you immediately, and you can watch it change when viewing in Portrait or Horizontal mode.
I’ve used the window.innerWidth and window.innerHeight as opposed to document.width and document.height, as the window gives us the total area, including scrollbars.
There is a detection script to check whether the device is a Retina device too, which allows you to optimise your graphics accordingly. As well as Retina detection, if you’re not on Retina, it’ll merely state ‘No Retina Device’ instead.
Alongside Retina, we have a devicePixelRatio detector which will add the pixel ratio into the page. For retina displays, this will show ’2′ showing the pixel density.
Here’s the CSS that goes with the widget, you can adopt it to fit your project. It uses position:fixed; to always remain in view. Tweak as you need, I’ve included some nice little icons to make the design more interesting, a semi-transparent background which you can also adjust so you can see some content underneath still.
You’ll need the ViewPort meta tag (supplied in the download) to get the width of your responsive page. Here’s the ViewPort tag to copy and paste otherwise:
Place the ViewPort meta tag in the head of your document and remember – this script needs to be inside the body tag, not in the head.