Div scrollbar width

Is there an easy way to get the scrollbar width using javascript / jquery? I need to get a div width that overflows + any scrollbar width.

thanks

+6
source share
4 answers

if you are using jquery try the following:

function getScrollbarWidth() { var div = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div></div>'); $('body').append(div); var w1 = $('div', div).innerWidth(); div.css('overflow-y', 'auto'); var w2 = $('div', div).innerWidth(); $(div).remove(); return (w1 - w2); } 

I use this in a project I'm working on, and it works like a charm. it gets the scrollbar width:

  • adding a div with overflowing contents to the body (in the invisible area, -200px top / left)
  • set overflow to hidden
  • get width
  • set overflow to auto (to get scroll bars)
  • get width
  • align both widths to get scrollbar width

so you will need to make the width of your div ( $('#mydiv').width() ) and add the scrollbar width:

 var completewidth = $('#mydiv').width() + getScrollbarWidth(); 
+12
source

try it

$("#myDiv")[0].scrollWidth

+3
source

Setting the div overflow to " scroll " automatically adds scrollbars (even if nothing is inside, scrollbars will be there, but gray). So just make a div, find the width, set the overflow to scroll and find the new width and return the difference:

 function getScrollBarWidth() { var helper = document.createElement('div'); helper.style = "width: 100px; height: 100px; overflow:hidden;" document.body.appendChild(helper); var bigger = helper.clientWidth; helper.style.overflow = "scroll"; var smaller = helper.clientWidth; document.body.removeChild(helper); return(bigger - smaller); } 
+2
source

Here is a simple version of javascript that is faster.

 function getScrollbarWidth() { var div, body, W = window.browserScrollbarWidth; if (W === undefined) { body = document.body, div = document.createElement('div'); div.innerHTML = '<div style="width: 50px; height: 50px; position: absolute; left: -100px; top: -100px; overflow: auto;"><div style="width: 1px; height: 100px;"></div></div>'; div = div.firstChild; body.appendChild(div); W = window.browserScrollbarWidth = div.offsetWidth - div.clientWidth; body.removeChild(div); } return W; }; 
0
source

Source: https://habr.com/ru/post/897759/


All Articles