Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
115
rated 0 times [  119] [ 4]  / answers: 1 / hits: 175356  / 12 Years ago, wed, november 14, 2012, 12:00:00

The following HTML will display a scroll bar on the right inside edge of div.container.



Is it possible to determine the width of that scroll bar?



<div class=container style=overflow-y:auto; height:40px;>
<div class=somethingBig></div>
</div>

More From » javascript

 Answers
430

This function should give you width of scrollbar



function getScrollbarWidth() {

// Creating invisible container
const outer = document.createElement('div');
outer.style.visibility = 'hidden';
outer.style.overflow = 'scroll'; // forcing scrollbar to appear
outer.style.msOverflowStyle = 'scrollbar'; // needed for WinJS apps
document.body.appendChild(outer);

// Creating inner element and placing it in the container
const inner = document.createElement('div');
outer.appendChild(inner);

// Calculating difference between container's full width and the child width
const scrollbarWidth = (outer.offsetWidth - inner.offsetWidth);

// Removing temporary elements from the DOM
outer.parentNode.removeChild(outer);

return scrollbarWidth;

}


Basic steps here are:




  1. Create hidden div (outer) and get it's offset width

  2. Force scroll bars to appear in div (outer) using CSS overflow property

  3. Create new div (inner) and append to outer, set its width to '100%' and get offset width

  4. Calculate scrollbar width based on gathered offsets



Working example here: http://jsfiddle.net/slavafomin/tsrmgcu9/



Update



If you're using this on a Windows (metro) App, make sure you set the -ms-overflow-style property of the 'outer' div to scrollbar, otherwise the width will not be correctly detected. (code updated)



Update #2
This will not work on Mac OS with the default Only show scrollbars when scrolling setting (Yosemite and up).


[#81993] Tuesday, November 13, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
deonkalvinw

Total Points: 409
Total Questions: 96
Total Answers: 89

Location: Saint Pierre and Miquelon
Member since Sun, Nov 27, 2022
2 Years ago
deonkalvinw questions
Sun, Feb 6, 22, 00:00, 2 Years ago
Tue, Dec 28, 21, 00:00, 2 Years ago
Sun, Aug 22, 21, 00:00, 3 Years ago
Sun, Mar 7, 21, 00:00, 3 Years ago
;