Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dom
communitycreator

What is the scrollWidth property in DOM?

Ayush Trivedi

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

scrollWidth in DOM is an HTML property that returns the scroll width of the HTML element.

The scroll width refers to the entire width of that element in the HTML page, even if it is not viewable due to the overflow property.

The element’s scroll width includes the width assigned in CSS property plus the padding, but it does not include the margin, border, or scrollbar.

Example

Let us see an example to find the scroll width of the div element.

Console

Code explanation

  • In lines 5-9: We have CSS properties for id elem, where we define backgroud-color, padding, and width.

  • In line 14: We have a paragraph p tag to display text.

  • In line 16: We have a button tag that has a change() function that is bound with the onclick event.

  • In line 18: We have a div element with an ID elem that we will use to get the element object.

  • In lines 23-27: We define a change() function that will be called with the click of the button from the HTML page. We use document.getElementById() to get the desired element of DOM, and then we apply scrollWidth, which will return the scroll width of the element. We print the value returned by scrollWidth on the console.

Output

We have successfully retrieved the scroll width of a div element. The console prints the total width, which is 5020px. The width also includes the padding, therefore the width of div(5000px) + top and bottom padding(10px + 10px = 20px) is 5020px. Remember that scroll width does not include the border, scrollbar, or margin.

RELATED TAGS

dom
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring