In this article, we are given an HTML document and the task is to get the height of the scrollbar using JavaScript. Following are the different approaches to solving this problem which are discussed below:
Approach 1: In this approach, a div element is created that contains a scrollbar. To get the height of the scroll bar the offsetHeight of the div is subtracted from the clientHeight of the div.
- OffsetHeight = Height of an element + Scrollbar Height.
- ClientHeight = Height of an element.
- Height of scrollbar = offsetHeight – clientHeight.
Example:
HTML
<!DOCTYPE HTML> < html > < head > < style > h1 { color:green; } #geek1 { width: 300px; overflow-y:hidden; border:1px solid black; white-space: nowrap; } #geek2 { font-size: 20px; font-weight: bold; } #geek4 { font-size: 24px; font-weight: bold; color: green; } </ style > </ head > < body > < center > < h1 >neveropen</ h1 > < p id = "geek2" ></ p > < div id = "geek1" > Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. </ div > < br > < button onclick = "geek3()" > Click Here </ button > < p id = "geek4" ></ p > < script > var element = document.getElementById('geek1'); var el_up = document.getElementById('geek2'); var el_down = document.getElementById('geek4'); el_up.innerHTML = "To get " + "the height of the scrollbar."; function geek3() { el_down.innerHTML = element.offsetHeight - element.clientHeight + "px"; } </ script > </ center > </ body > </ html > |
Output:
Approach 2: In this approach, an outer div element is created and in this outer div element, an inner div element is also created. To get the height of the scroll bar the height of the inner div is subtracted from the outer div.
Example:
HTML
<!DOCTYPE HTML> < html > < head > < style > h1 { color:green; } #geek1 { width: 300px; overflow-y:hidden; border:1px solid black; white-space: nowrap; } #geek2 { font-size: 20px; font-weight: bold; } #geek4 { font-size: 24px; font-weight: bold; color: green; } </ style > </ head > < body > < center > < h1 >neveropen</ h1 > < p id = "geek2" ></ p > < div id = "geek1" > < div id = "geek5" > Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. </ div > </ div > < br > < button onclick = "geek3()" > Click Here </ button > < p id = "geek4" ></ p > < script > var element = document.getElementById('geek1'); var el_up = document.getElementById('geek2'); var el_down = document.getElementById('geek4'); el_up.innerHTML = "To get " + "the height of the scrollbar."; function geek3() { var child = document.querySelector("#geek5"); var scroll = child.parentNode.offsetHeight - child.offsetHeight; el_down.innerHTML = scroll + "px"; } </ script > </ center > </ body > </ html > |
Output: