jQuery get browser width including scrollBar

Posted by Damodar Bashyal on September 06, 2013

 

First Check if scrollbar is on:

if($(document).height() > $(window).height()){... srcollbar is on ...}

Now lets create a function to find the width of the scrollbar:

function getScrollBarWidth(){
	if($(document).height() > $(window).height()){
		$('body').append('<div id="fakescrollbar" style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"></div>');
		fakeScrollBar = $('#fakescrollbar');
		fakeScrollBar.append('<div style="height:100px;">&nbsp;</div>');
		var w1 = fakeScrollBar.find('div').innerWidth();
		fakeScrollBar.css('overflow-y', 'scroll');
		var w2 = $('#fakescrollbar').find('div').html('html is required to init new width.').innerWidth();
		fakeScrollBar.remove();
		return (w1-w2);
	}
	return 0;
}

We know how to get browser window width using jQuery width().

var browserWidthWithOutScrollBar = $(window).width();

So if we add scroll width, we can find the current browser width which is used by css @media viewport width (thats what I found in my case, not sure if that applies to your case ;) )

var scrollWidth = getScrollBarWidth();
var browserWidthIncludingScrollBar = ($(window).width() + scrollWidth);

Matt_sounddesigner posted on - Saturday 28th of June 2014 10:54:19 AM

Thanks a lot ! I combined it with css media queries too and it works like a charm !

steve posted on - Sunday 27th of April 2014 11:03:26 AM

perfect, thank you
i needed excactly this, for working together with css @media viewport width.
its working perfect.
 
not published on website


QR Code: jQuery get browser width including scrollBar