I am really confused by the different properties that exist in JavaScript for getting the dimensions of a document and how to get those numbers. Can someone recommend a good place to start to understand how I would get the size of the document and position stuff correctly?
Confused by document dimensions in JavaScript
3.9k views Asked by user1019031 At
1
There are 1 answers
Related Questions in JAVASCRIPT
- Using Puppeteer to scrape a public API only when the data changes
- inline SVG text (js)
- An array of images and a for loop display the buttons. How to assign each button to open its own block by name?
- Storing the preferred font-size in localStorage
- Simple movie API request not showing up in the console log
- Authenticate Flask rest API
- Deploying sveltekit app with gunjs on vercel throws cannot find module './lib/text-encoding'
- How to request administrator rights?
- mp4 embedded videos within github pages website not loading
- Scrimba tutorial was working, suddenly stopped even trying the default
- In Datatables, start value resets to 0, when column sorting
- How do I link two models in mongoose?
- parameter values only being sent to certain columns in google sheet?
- Run main several times of wasm in browser
- Variable inside a Variable, not updating
Related Questions in DOCUMENT
- PHP Dom merge documents
- Send document using Telegram bot API Javascript
- Design and Fill printable documents in C# .NET
- How do I add various document types to a Firebird BLOB field with Delphi
- Preserving word document formatting - footnotes, end notes everything while rewriting via code
- Mongodb find operation in embedded document
- How to parse a document and prompt user input for placeholders in a React app
- Javascript that displays different page every hour needs to open in new window
- DOMPDF - Script to convert HTML to PDF using DomPdf library
- Issues with text copying in the Syncfusion Document Editor
- Issue while concatenating 2 docx files
- excel file is not being picked and not readable as well in expo reactnative
- How to filter non-document-type in aiogram v.2s?
- Module Not Found Error: "langchain.chains.question_answering"
- View XPS and PDF in browser
Related Questions in DIMENSIONS
- Select the data.frame with maximum dimensions from a list of data.frames
- Get toast notification dimensions (size, rect)
- Creating a moving correlation Heat Map using treeclim, mysterious hidden column?
- Python: Plot array as function of time
- Telegram gif dimensions are invalid
- GA4 API User Segment vs Session Segment
- How to set dimension of arrays inside nested structs
- Why is out channels in pyg autoencoder set to 16?
- PowerApps - screen size issues
- How to make a function work with different sized meshgrid/linspace inputs
- how to provide constraint for convex problem in python
- python-docx unable to create a table with desired dimensions
- Error incorrect number of dimensions in msprep for multi-state modelling in R
- Why my Android device is applying sw410dp styles when it is 480dp?
- dimentions of images red channel to FC network input
Related Questions in SCROLLBARS
- JQuery UI Autocomplete with categories and scrollbar
- How to add scrollbars in a content area of a full screen web app i.e. 100% height of screen using CSS
- The scrollbar of the child HorizontalScrollView has been separated from the scrollbar of the parent ScrollView
- css - shrink element instead of whole page
- Editing mac scrollbars
- why position of BottomNavigationView depends on ScrollView scrollbars?
- Tkinter: Fully functional scrolledFrame with autohiding scrollbar, except for border
- Custom Scrollbars in Firefox
- C# DataGridView doesn't show Scrollbars when filling from Task
- How to get height and width of viewport without creating scrollbars?
- ScrollableControl resets ScrollBar Value after user scrolled
- GTK3 Drawing Window Size?
- Tkinter Listbox width interferes with scrollbars
- GWT scrollbars not appearing
- JavaFX ScrollPane not showing ScrollBars until mouse is clicked on the ScrollBar
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
I'll try to answer as simply as I can.
The Document and Viewport
In terms of geometry, there are two sets of dimensions to be aware of; the document dimensions, which reflect the entire size of the loaded page, including the content beyond the bottom of the window and the viewport dimensions, which reflect the size of the visible part of the document that is immediately displayed in the window.
When you scroll down, the viewport moves down over the document by a certain number of pixels. In other words, the viewport is the actual browser window "border" (the toolbars, menus, tabs, and so on).
The confusion comes from the fact that depending on the browser and mode, different properties are used to get the dimensions of a document and viewport, and they return different results depending on scrollbars. But we'll come back to this.
Dimensions Overview
There are a number of properties available to you from the get-go in javascript which give you different dimensions.
Screen resolution:
window.screen.width -HeightAvailable screen space (same as monitor resolution) minus docks, toolbars and other UI elements:
window.screen.availWidth -Height.Document dimensions:
document.documentElement.offsetWidth -HeightNote: These numbers do not include the scrollbars.Viewport dimensions:
window.innerWidth -HeightThese numbers include the scrollbars.
This is not available in IE 8- and IE9, so if IE, test for the
document.compatMode === "CSS1Compat"and if true, usedocument.documentElement.clientWidth -Height, and for quirks mode usedocument.body.clientWidth -Height.A note about document dimensions
As per above,
document.documentElement.offsetWidth/Heightprovides you with the actual size of the document. One caveat to this is that scrollbars work differently between browsers. For example, IE9 will always display a vertical scrollbar even if the document height is less than the viewport height. Safari/Chrome doesn't have scrollbars on OS X Lion. Chrome on PC will not display vertical scrollbars unless it needs to.So you may bump into inconsistencies and the Scrollbar shifts content problem. Imagine you have an absolutely positioned and centred element. Because CSS calculates the "centre" relative to the document dimensions and not the viewport dimensions, when say, Google adds the scrollbars, your content may "jump" a bit to the left as the "document centre" changes. So you may need to write JS to compensate for this effect if it bothers you, or maybe someone here can write a quick JS function to calculate document dimensions with scrollbars included.
Scrollbar Position and Dimensions
While some methods in JavaScript work with document coordinates, others work with viewport coordinates, and often this is not what you want. For example, if you have an element's top edge at 20px in document coordinates, and you scroll the page down by 20px, the top edge of that element will be at 0px relative to the top viewport coordinate. So to convert between the two systems, you first need to know by how many pixels a user has scrolled the document, and then add that number to the viewport to compensate (look at example below).
I also found these helpful:
http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
http://www.quirksmode.org/mobile/viewports.html
And here's a quick cross-browser module I mucked up to help you:
You can for example do
console.log(dimensions.viewportWidth())to get the viewport width.Hope this helps you :)