How to reliably get screen width WITH the scrollbar - javascript

Is there a way to reliably tell a browser's viewport width that includes the scrollbar, but not the rest of browser window)?
None of the properties listed here tell me the width of the screen INCLUDING the scrollbar (if present)

I figured out how to accurately get the viewport width WITH the scrollbar using some code from: http://andylangton.co.uk/blog/development/get-viewport-size-width-and-height-javascript
Put this inside your $(document).ready(function()
$(document).ready(function(){
$(window).on("resize", function(){
function viewport() {
var e = window, a = 'inner';
if (!('innerWidth' in window )) {
a = 'client';
e = document.documentElement || document.body;
}
return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}
});
// Get the correct window sizes with these declarations
windowHeight = viewport().height;
windowWidth = viewport().width;
});
What it Does:
When your page is 'ready' or is resized, the function calculates the correct window height and width (including scrollbar).

I assume you want to know the viewport width with scrollbar included, because the screen it self does not have a scrollbar. In fact the Screen width and heigth will be the computer screen resolution itself, so I'm not sure what you mean with screen width with the scroll bar.
The viewport however, the area where only the page (and scroll bars) is presented to the user, meaning, no browser menus, no bookmarks or whatever, only the page rendered, is where such scroll bar may be present.
Assuming you want that, you can measure the client browser viewport size while taking into account the size of the scroll bars this way.
First don't forget to set you body tag to be 100% width and height just to make sure the measurement is accurate.
body {
width: 100%;
// if you wish to also measure the height don't forget to also set it to 100% just like this one.
}
Afterwards you can measure the width at will.
Sample
// First you forcibly request the scroll bars to be shown regardless if you they will be needed or not.
$('body').css('overflow', 'scroll');
// Viewport width with scroll bar.
var widthWithScrollBars = $(window).width();
// Now if you wish to know how many pixels the scroll bar actually has
// Set the overflow css property to forcibly hide the scroll bar.
$('body').css('overflow', 'hidden');
// Viewport width without scroll bar.
var widthNoScrollBars = $(window).width();
// Scroll bar size for this particular client browser
var scrollbarWidth = widthWithScrollBars - widthNoScrollBars;
// Set the overflow css property back to whatever value it had before running this code. (default is auto)
$('body').css('overflow', 'auto');
Hope it helps.

As long as body is 100%, document.body.scrollWidth will work.
Demo: http://jsfiddle.net/ThinkingStiff/5j3bY/
HTML:
<div id="widths"></div>
CSS:
body, html
{
margin: 0;
padding: 0;
width: 100%;
}
div
{
height: 1500px;
}
Script:
var widths = 'viewport width (body.scrollWidth): '
+ document.body.scrollWidth + '<br />'
+ 'window.innerWidth: ' + window.innerWidth + '<br />';
document.getElementById( 'widths' ).innerHTML = widths;
I put a tall div in the demo to force a scroll bar.

Currently the new vw and vh css3 properties will show full size including scrollbar.
body {
width:100vw;
height:100vh;
}
There is some discussion online if this is a bug or not.

there is nothing after scrollbar so "rest of the window" is what?
But yes one way to do it is make another wrapper div in body where everything goes and body has overflow:none; height:100%; width:100%; on it, wrapper div also also has 100% width and height. and overflow to scroll. SO NOW...the width of wrapper would be the width of viewport
See Example: http://jsfiddle.net/techsin/8fvne9fz/
html,body {
height: 100%;
overflow: hidden;
}
.wrapper {
width: 100%;
height: 100%;
overflow: auto;
}

With jQuery you can calculate the browser's scrollbar width by getting the width difference when overflow: hidden is set and overflow: scroll is set.
The difference in width will be the size of the scrollbar.
Here is a simple example that shows how you could do this.

You can get the window width with scrollbar , that way:
function scrollbar_width() {
if (jQuery('body').height() > jQuery(window).height()) {
/* Modified from: http://jdsharp.us/jQuery/minute/calculate-scrollbar-width.php */
var calculation_content = jQuery('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div>');
jQuery('body').append(calculation_content);
var width_one = jQuery('div', calculation_content).innerWidth();
calculation_content.css('overflow-y', 'scroll');
var width_two = jQuery('div', calculation_content).innerWidth();
jQuery(calculation_content).remove();
return (width_one - width_two);
}
return 0;
}

Check out vw: http://dev.w3.org/csswg/css-values/#viewport-relative-lengths
body {
width: 100vw;
}
http://caniuse.com/#search=vw

This is my solution for removing the 'scrollbar shadow', because scrollWidth didn't work for me:
canvas.width = element.offsetWidth;
canvas.height = element.offsetHeight;
canvas.width = element.offsetWidth;
canvas.height = element.offsetHeight;
It's easy, but it works. Make sure to add a comment explaining why you assign the same value twice :)

Related

How to get the height of the overall page using jquery

I tried:
$(document).height();
$("#body").height();
but it make doesn't give an exact value.
You are looking for the scroll height property
var el = document.body;
console.log(el.scrollHeight); // height with overflow
body {
height: 100vh;
}
.div {
height: 10000px;
}
<div class="div">
</div>
Check out the specs for the height function:
// Returns height of browser viewport
$( window ).height();
// Returns height of HTML document
$( document ).height();
The "height of the overall page" I interpret to be the size of the viewport. If you're looking for something a little more robust...
function getPageHeight ()
{
//If the content is smaller than the viewport, return the height
//of the screen. Otherwise, return the height of the content.
return Math.max ($(window).height (), $('body').height ());
}

How to access screen size within javascript file [duplicate]

How can I get windowWidth, windowHeight, pageWidth, pageHeight, screenWidth, screenHeight, pageX, pageY, screenX, screenY which will work in all major browsers?
You can get the size of the window or document with jQuery:
// Size of browser viewport.
$(window).height();
$(window).width();
// Size of HTML document (same as pageHeight/pageWidth in screenshot).
$(document).height();
$(document).width();
For screen size you can use the screen object:
window.screen.height;
window.screen.width;
This has everything you need to know: Get viewport/window size
but in short:
var win = window,
doc = document,
docElem = doc.documentElement,
body = doc.getElementsByTagName('body')[0],
x = win.innerWidth || docElem.clientWidth || body.clientWidth,
y = win.innerHeight|| docElem.clientHeight|| body.clientHeight;
alert(x + ' × ' + y);
Fiddle
Please stop editing this answer. It's been edited 22 times now by different people to match their code format preference. It's also been pointed out that this isn't required if you only want to target modern browsers - if so you only need the following:
const width = window.innerWidth || document.documentElement.clientWidth ||
document.body.clientWidth;
const height = window.innerHeight|| document.documentElement.clientHeight||
document.body.clientHeight;
console.log(width, height);
Here is a cross browser solution with pure JavaScript (Source):
var width = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
var height = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
A non-jQuery way to get the available screen dimension. window.screen.width/height has already been put up, but for responsive webdesign and completeness sake I think its worth to mention those attributes:
alert(window.screen.availWidth);
alert(window.screen.availHeight);
http://www.quirksmode.org/dom/w3c_cssom.html#t10 :
availWidth and availHeight - The available width and height on the
screen (excluding OS taskbars and such).
But when we talk about responsive screens and if we want to handle it using jQuery for some reason,
window.innerWidth, window.innerHeight
gives the correct measurement. Even it removes the scroll-bar's extra space and we don't need to worry about adjusting that space :)
Full 2020
I am surprised that question have about 10 years and it looks like so far nobody has given a full answer (with 10 values) yet. So I carefully analyse OP question (especially picture) and have some remarks
center of coordinate system (0,0) is in the viewport (browser window without bars and main borders) top left corner and axes are directed to right and down (what was marked on OP picture) so the values of pageX, pageY, screenX, screenY must be negative (or zero if page is small or not scrolled)
for screenHeight/Width OP wants to count screen height/width including system menu bar (eg. in MacOs) - this is why we NOT use .availWidth/Height (which not count it)
for windowWidth/Height OP don't want to count size of scroll bars so we use .clientWidth/Height
the screenY - in below solution we add to position of top left browser corner (window.screenY) the height of its menu/tabls/url bar). But it is difficult to calculate that value if download-bottom bar appears in browser and/or if developer console is open on page bottom - in that case this value will be increased of size of that bar/console height in below solution. Probably it is impossible to read value of bar/console height to make correction (without some trick like asking user to close that bar/console before measurements...)
pageWidth - in case when pageWidth is smaller than windowWidth we need to manually calculate size of <body> children elements to get this value (we do example calculation in contentWidth in below solution - but in general this can be difficult for that case)
for simplicity I assume that <body> margin=0 - if not then you should consider this values when calculate pageWidth/Height and pageX/Y
function sizes() {
const contentWidth = [...document.body.children].reduce(
(a, el) => Math.max(a, el.getBoundingClientRect().right), 0)
- document.body.getBoundingClientRect().x;
return {
windowWidth: document.documentElement.clientWidth,
windowHeight: document.documentElement.clientHeight,
pageWidth: Math.min(document.body.scrollWidth, contentWidth),
pageHeight: document.body.scrollHeight,
screenWidth: window.screen.width,
screenHeight: window.screen.height,
pageX: document.body.getBoundingClientRect().x,
pageY: document.body.getBoundingClientRect().y,
screenX: -window.screenX,
screenY: -window.screenY - (window.outerHeight-window.innerHeight),
}
}
// TEST
function show() {
console.log(sizes());
}
body { margin: 0 }
.box { width: 3000px; height: 4000px; background: red; }
<div class="box">
CAUTION: stackoverflow snippet gives wrong values for screenX-Y,
but if you copy this code to your page directly the values will be right<br>
<button onclick="show()" style="">CALC</button>
</div>
I test it on Chrome 83.0, Safari 13.1, Firefox 77.0 and Edge 83.0 on MacOs High Sierra
Graphical answer:
(............)
function wndsize(){
var w = 0;var h = 0;
//IE
if(!window.innerWidth){
if(!(document.documentElement.clientWidth == 0)){
//strict mode
w = document.documentElement.clientWidth;h = document.documentElement.clientHeight;
} else{
//quirks mode
w = document.body.clientWidth;h = document.body.clientHeight;
}
} else {
//w3c
w = window.innerWidth;h = window.innerHeight;
}
return {width:w,height:h};
}
function wndcent(){
var hWnd = (arguments[0] != null) ? arguments[0] : {width:0,height:0};
var _x = 0;var _y = 0;var offsetX = 0;var offsetY = 0;
//IE
if(!window.pageYOffset){
//strict mode
if(!(document.documentElement.scrollTop == 0)){offsetY = document.documentElement.scrollTop;offsetX = document.documentElement.scrollLeft;}
//quirks mode
else{offsetY = document.body.scrollTop;offsetX = document.body.scrollLeft;}}
//w3c
else{offsetX = window.pageXOffset;offsetY = window.pageYOffset;}_x = ((wndsize().width-hWnd.width)/2)+offsetX;_y = ((wndsize().height-hWnd.height)/2)+offsetY;
return{x:_x,y:_y};
}
var center = wndcent({width:350,height:350});
document.write(center.x+';<br>');
document.write(center.y+';<br>');
document.write('<DIV align="center" id="rich_ad" style="Z-INDEX: 10; left:'+center.x+'px;WIDTH: 350px; POSITION: absolute; TOP: '+center.y+'px; HEIGHT: 350px"><!--К сожалению, у Вас не установлен flash плеер.--></div>');
You can also get the WINDOW width and height, avoiding browser toolbars and other stuff. It is the real usable area in browser's window.
To do this, use:
window.innerWidth and window.innerHeight properties (see doc at w3schools).
In most cases it will be the best way, in example, to display a perfectly centred floating modal dialog. It allows you to calculate positions on window, no matter which resolution orientation or window size is using the browser.
To check height and width of your current loaded page of any website using "console" or after clicking "Inspect".
step 1: Click the right button of mouse and click on 'Inspect' and then click 'console'
step 2: Make sure that your browser screen should be not in 'maximize' mode. If the browser screen is in 'maximize' mode, you need to first click the maximize button (present either at right or left top corner) and un-maximize it.
step 3: Now, write the following after the greater than sign ('>') i.e.
> window.innerWidth
output : your present window width in px (say 749)
> window.innerHeight
output : your present window height in px (say 359)
Complete guide related to Screen sizes
JavaScript
For height:
document.body.clientHeight // Inner height of the HTML document body, including padding
// but not the horizontal scrollbar height, border, or margin
screen.height // Device screen height (i.e. all physically visible stuff)
screen.availHeight // Device screen height minus the operating system taskbar (if present)
window.innerHeight // The current document's viewport height, minus taskbars, etc.
window.outerHeight // Height the current window visibly takes up on screen
// (including taskbars, menus, etc.)
Note: When the window is maximized this will equal screen.availHeight
For width:
document.body.clientWidth // Full width of the HTML page as coded, minus the vertical scroll bar
screen.width // Device screen width (i.e. all physically visible stuff)
screen.availWidth // Device screen width, minus the operating system taskbar (if present)
window.innerWidth // The browser viewport width (including vertical scroll bar, includes padding but not border or margin)
window.outerWidth // The outer window width (including vertical scroll bar,
// toolbars, etc., includes padding and border but not margin)
Jquery
For height:
$(document).height() // Full height of the HTML page, including content you have to
// scroll to see
$(window).height() // The current document's viewport height, minus taskbars, etc.
$(window).innerHeight() // The current document's viewport height, minus taskbars, etc.
$(window).outerHeight() // The current document's viewport height, minus taskbars, etc.
For width:
$(document).width() // The browser viewport width, minus the vertical scroll bar
$(window).width() // The browser viewport width (minus the vertical scroll bar)
$(window).innerWidth() // The browser viewport width (minus the vertical scroll bar)
$(window).outerWidth() // The browser viewport width (minus the vertical scroll bar)
Reference: https://help.optimizely.com/Build_Campaigns_and_Experiments/Use_screen_measurements_to_design_for_responsive_breakpoints
With the introduction of globalThis in ES2020 you can use properties like.
For screen size:
globalThis.screen.availWidth
globalThis.screen.availHeight
For Window Size
globalThis.outerWidth
globalThis.outerHeight
For Offset:
globalThis.pageXOffset
globalThis.pageYOffset
...& so on.
alert("Screen Width: "+ globalThis.screen.availWidth +"\nScreen Height: "+ globalThis.screen.availHeight)
If you need a truly bulletproof solution for the document width and height (the pageWidth and pageHeight in the picture), you might want to consider using a plugin of mine, jQuery.documentSize.
It has just one purpose: to always return the correct document size, even in scenarios when jQuery and other methods fail. Despite its name, you don't necessarily have to use jQuery – it is written in vanilla Javascript and works without jQuery, too.
Usage:
var w = $.documentWidth(),
h = $.documentHeight();
for the global document. For other documents, e.g. in an embedded iframe you have access to, pass the document as a parameter:
var w = $.documentWidth( myIframe.contentDocument ),
h = $.documentHeight( myIframe.contentDocument );
Update: now for window dimensions, too
Ever since version 1.1.0, jQuery.documentSize also handles window dimensions.
That is necessary because
$( window ).height() is buggy in iOS, to the point of being useless
$( window ).width() and $( window ).height() are unreliable on mobile because they don't handle the effects of mobile zooming.
jQuery.documentSize provides $.windowWidth() and $.windowHeight(), which solve these issues. For more, please check out the documentation.
I wrote a small javascript bookmarklet you can use to display the size. You can easily add it to your browser and whenever you click it you will see the size in the right corner of your browser window.
Here you find information how to use a bookmarklet
https://en.wikipedia.org/wiki/Bookmarklet
Bookmarklet
javascript:(function(){!function(){var i,n,e;return n=function(){var n,e,t;return t="background-color:azure; padding:1rem; position:fixed; right: 0; z-index:9999; font-size: 1.2rem;",n=i('<div style="'+t+'"></div>'),e=function(){return'<p style="margin:0;">width: '+i(window).width()+" height: "+i(window).height()+"</p>"},n.html(e()),i("body").prepend(n),i(window).resize(function(){n.html(e())})},(i=window.jQuery)?(i=window.jQuery,n()):(e=document.createElement("script"),e.src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js",e.onload=n,document.body.appendChild(e))}()}).call(this);
Original Code
The original code is in coffee:
(->
addWindowSize = ()->
style = 'background-color:azure; padding:1rem; position:fixed; right: 0; z-index:9999; font-size: 1.2rem;'
$windowSize = $('<div style="' + style + '"></div>')
getWindowSize = ->
'<p style="margin:0;">width: ' + $(window).width() + ' height: ' + $(window).height() + '</p>'
$windowSize.html getWindowSize()
$('body').prepend $windowSize
$(window).resize ->
$windowSize.html getWindowSize()
return
if !($ = window.jQuery)
# typeof jQuery=='undefined' works too
script = document.createElement('script')
script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js'
script.onload = addWindowSize
document.body.appendChild script
else
$ = window.jQuery
addWindowSize()
)()
Basically the code is prepending a small div which updates when you resize your window.
In some cases related with responsive layout $(document).height() can return wrong data that displays view port height only.
For example when some div#wrapper has height:100%, that #wrapper can be stretched by some block inside it. But it's height still will be like viewport height. In such situation you might use
$('#wrapper').get(0).scrollHeight
That represents actual size of wrapper.
I developed a library for knowing the real viewport size for desktops and mobiles browsers, because viewport sizes are inconsistents across devices and cannot rely on all the answers of that post (according to all the research I made about this) : https://github.com/pyrsmk/W
Sometimes you need to see the width/height changes while resizing the window and inner content.
For that I've written a little script that adds a log box that dynamicly monitors all the resizing and almost immediatly updates.
It adds a valid HTML with fixed position and high z-index, but is small enough, so you can:
use it on an actual site
use it for testing mobile/responsive
views
Tested on: Chrome 40, IE11, but it is highly possible to work on other/older browsers too ... :)
function gebID(id){ return document.getElementById(id); }
function gebTN(tagName, parentEl){
if( typeof parentEl == "undefined" ) var parentEl = document;
return parentEl.getElementsByTagName(tagName);
}
function setStyleToTags(parentEl, tagName, styleString){
var tags = gebTN(tagName, parentEl);
for( var i = 0; i<tags.length; i++ ) tags[i].setAttribute('style', styleString);
}
function testSizes(){
gebID( 'screen.Width' ).innerHTML = screen.width;
gebID( 'screen.Height' ).innerHTML = screen.height;
gebID( 'window.Width' ).innerHTML = window.innerWidth;
gebID( 'window.Height' ).innerHTML = window.innerHeight;
gebID( 'documentElement.Width' ).innerHTML = document.documentElement.clientWidth;
gebID( 'documentElement.Height' ).innerHTML = document.documentElement.clientHeight;
gebID( 'body.Width' ).innerHTML = gebTN("body")[0].clientWidth;
gebID( 'body.Height' ).innerHTML = gebTN("body")[0].clientHeight;
}
var table = document.createElement('table');
table.innerHTML =
"<tr><th>SOURCE</th><th>WIDTH</th><th>x</th><th>HEIGHT</th></tr>"
+"<tr><td>screen</td><td id='screen.Width' /><td>x</td><td id='screen.Height' /></tr>"
+"<tr><td>window</td><td id='window.Width' /><td>x</td><td id='window.Height' /></tr>"
+"<tr><td>document<br>.documentElement</td><td id='documentElement.Width' /><td>x</td><td id='documentElement.Height' /></tr>"
+"<tr><td>document.body</td><td id='body.Width' /><td>x</td><td id='body.Height' /></tr>"
;
gebTN("body")[0].appendChild( table );
table.setAttribute(
'style',
"border: 2px solid black !important; position: fixed !important;"
+"left: 50% !important; top: 0px !important; padding:10px !important;"
+"width: 150px !important; font-size:18px; !important"
+"white-space: pre !important; font-family: monospace !important;"
+"z-index: 9999 !important;background: white !important;"
);
setStyleToTags(table, "td", "color: black !important; border: none !important; padding: 5px !important; text-align:center !important;");
setStyleToTags(table, "th", "color: black !important; border: none !important; padding: 5px !important; text-align:center !important;");
table.style.setProperty( 'margin-left', '-'+( table.clientWidth / 2 )+'px' );
setInterval( testSizes, 200 );
EDIT: Now styles are applied only to logger table element - not to all tables - also this is a jQuery-free solution :)
You can use the Screen object to get this.
The following is an example of what it would return:
Screen {
availWidth: 1920,
availHeight: 1040,
width: 1920,
height: 1080,
colorDepth: 24,
pixelDepth: 24,
top: 414,
left: 1920,
availTop: 414,
availLeft: 1920
}
To get your screenWidth variable, just use screen.width, same with screenHeight, you would just use screen.height.
To get your window width and height, it would be screen.availWidth or screen.availHeight respectively.
For the pageX and pageY variables, use window.screenX or Y. Note that this is from the VERY LEFT/TOP OF YOUR LEFT/TOP-est SCREEN. So if you have two screens of width 1920 then a window 500px from the left of the right screen would have an X value of 2420 (1920+500). screen.width/height, however, display the CURRENT screen's width or height.
To get the width and height of your page, use jQuery's $(window).height() or $(window).width().
Again using jQuery, use $("html").offset().top and $("html").offset().left for your pageX and pageY values.
here is my solution!
// innerWidth
const screen_viewport_inner = () => {
let w = window,
i = `inner`;
if (!(`innerWidth` in window)) {
i = `client`;
w = document.documentElement || document.body;
}
return {
width: w[`${i}Width`],
height: w[`${i}Height`]
}
};
// outerWidth
const screen_viewport_outer = () => {
let w = window,
o = `outer`;
if (!(`outerWidth` in window)) {
o = `client`;
w = document.documentElement || document.body;
}
return {
width: w[`${o}Width`],
height: w[`${o}Height`]
}
};
// style
const console_color = `
color: rgba(0,255,0,0.7);
font-size: 1.5rem;
border: 1px solid red;
`;
// testing
const test = () => {
let i_obj = screen_viewport_inner();
console.log(`%c screen_viewport_inner = \n`, console_color, JSON.stringify(i_obj, null, 4));
let o_obj = screen_viewport_outer();
console.log(`%c screen_viewport_outer = \n`, console_color, JSON.stringify(o_obj, null, 4));
};
// IIFE
(() => {
test();
})();
This how I managed to get the screen width in React JS Project:
If width is equal to 1680 then return 570 else return 200
var screenWidth = window.screen.availWidth;
<Label style={{ width: screenWidth == "1680" ? 570 : 200, color: "transparent" }}>a </Label>
Screen.availWidth

make div 100% of browser height depending on length of content

I have 2 divs, a navigation and a main content in a bootstrap grid system. The length of either can vary depending on amount of content. I need them both styled to fill 100% of the browser window IF neither has the content to reach the bottom naturally. But if at least one of the divs has more content than the length of the browser window, I need to be able to scroll down the page with the styles of both divs remaining in tact and both have a height of the longer of the 2 divs.
I'm currently using a javascript resize function which seems to work but not in the case where neither div is long enough to fill the height of the browser window. Any suggestions?
HTML
<div class="row">
<div id="nav" class="col-xs-2">
Variable Height Navigation
</div>
<div id="main" class="col-xs-10">
Variable Height Content
</div>
</div>
Javascript
function resize() {
var h = (document.height !== undefined) ? document.height : document.body.offsetHeight;
document.getElementById("nav").style.height = h + "px";
}
resize();
window.onresize = function () {
resize();
};
I am trying to understand you question, and if I'm correct what you are looking for is:
Both divs need to be equally high
They need be at least the height of the screen
They need to take the height of the highest div
So let's try to achieve this goal as simply as possible:
var main = document.getElementById('main');
var nav = document.getElementById('nav');
function resize(){
var highest;
// Set the divs back to autosize, so we can measure their content height correctly.
main.style.height = 'auto';
nav.style.height = 'auto';
// Find the highest div and store its height.
highest = main.clientHeight > nav.clientHeight
? main.clientHeight
: nav.clientHeight;
// Check if the highest value is the div or the window.
highest = highest > window.innerHeight
? highest
: window.innerHeight;
// Assign the newly found value
main.style.height = highest + 'px';
nav.style.height = highest + 'px';
}
resize();
// Also, you don't need to wrap it in a function.
window.resize = resize;
// However, better would be:
window.addEventListener('resize', resize, false);
#main, #nav {
width: 100%;
height: auto;
}
#main { background: red; }
#nav { background: green; }
<div id="main"></div>
<div id="nav"></div>
Now, If you aren't bothered with the actual sameness in heiught of both divs but just want them to at least be one screenful, you should consider using CSS:
html, body { height: 100%; }
#nav, #main { min-height: 100%; }
I think that is the better solution (no Javascript!) and sort-of does what you want, bar the fact that you won't have to equally high div elements. However, you would barely notice it as each will at least fill the page.
You could try using viewport height:
For example:
#nav {
min-height: 100vh;
}
#main {
min-height: 100vh;
}
See Bootply.
This will also remove the need for JavaScript.

Change position of div based on content & viewport height using jquery

I want to have a div be fixed at the bottom of the window when the window is taller than the content height. If the content height is taller than the window height, I want the div position to remain relative.
I currently have this mostly working, however I don't want the div to overlap the content at all. I tried various forms of below, but still not working:
var body = content+bottomBar
if (body > viewport) {
$(".bottom-bar").css({
'position':'relative'
});
} else {
$(".bottom-bar").css({
'position': 'fixed'
})
}
I also am having trouble getting the window.resize to work.
Any help would be appreciated!
http://jsfiddle.net/no05x1vx/1/
Referring to the jsfiddle linked by the OP, here are a few changes to make the code work as expected, please see the comments:
var content = $(".content").height()
var viewport = $(window).height();
// Use innerHeight here as the bottom-bar div has height 0 and padding 60px
// .height() would return 0
var bottomBar = $(".bottom-bar").innerHeight();
var body = parseInt(content)+parseInt(bottomBar)
$(window).on('resize', function(){
// Get new viewport height
viewport = $(window).height();
if (content > (viewport-bottomBar) ) {
$(".bottom-bar").css({
'position':'relative'
});
} else {
$(".bottom-bar").css({
'position': 'fixed'
})
}
});
// Trigger resize after page load (to avoid repeated code)
$(document).ready(function(){
$(window).resize();
});

How do you reduce the scrollable height of a div with scaled content?

I have a scrollable div that I zoom/scale the content of using css3 transform. It works fine if I'm zooming in (scaling up the content) but I've noticed that when scaling down, below 100%, the amount that you can scroll vertically of the container div does not reduce.
I've made a jsfiddle to illustrate this
CSS:
.scrollable
{
height: 250px;
width: 250px;
overflow: auto;
background-color: green;
}
.content
{
height :500px;
width : 500px;
background: linear-gradient(red, blue);
...
}
JS/jquery:
function scaleContent(newScale){
var $content = $("#content");
var scaleString = "scale("+newScale+")";
//var height = (newScale<1)? $("#content").height()/scale*newScale : originalHeight;
$content.css({
'-webkit-transform' : scaleString,
'-webkit-transform-origin' : '0 0',
...
//'height' : height +'px'
});
scale=newScale;
}
The actual scaling and the amount that you can scroll horizontally works perfectly, but the amount you can scroll vertically doesn't change below 100%.
Note: the amount you can scroll vertically appears to change on the first scaledown/zoomout, but this is simply because the horizontal scrollbar is removed.
I tried to manually change the height of the content, but this just messed with the content dimensions (duh). That's the commented-out height code.
The ellipses are where I've repeated things for other browsers.
I've managed to come up with one solution, though it's probably not the best. I introduced another div around the content, which I call the view wrapper. I set its overflow to "hidden" and manually set its width and height to match what the scaled content should be.
CSS:
.viewwrapper{
height :500px;
width : 500px;
overflow: hidden
}
JS:
function scaleContent(newScale){
var $content = $("#content");
var scaleString = "scale("+newScale+")";
var $viewwrapper = $("#viewwrapper");
var height = $content.height()/newScale;
var width = $content.width()/newScale;
$viewwrapper.height(height);
$viewwrapper.width(width);
$content.css({
'-webkit-transform' : scaleString,
'-webkit-transform-origin' : '0 0',
...
});
}
JS Fiddle
Update:
This won't work if you're using jQuery 3.0 or 3.1. The read behaviour of the height and width functions has changed, so they return the scaled values. To fix the above code for those versions you can just say.
function scaleContent(newScale){
var $content = $("#content");
var scaleString = "scale("+newScale+")";
var $viewwrapper = $("#viewwrapper");
$viewwrapper.height($content.height());
$viewwrapper.width($content.width());
$content.css({
'-webkit-transform' : scaleString,
'-webkit-transform-origin' : '0 0',
...
});
}
JSFiddle using jQuery 3.0
However this probably won't make it into future versions of jQuery.
Update 2:
You might see unnecessary scrollbars in Chrome when you zoom out of the content. This is down to a Chrome bug.
you're applying transformations to your #content div, but the outside div, #scrollable has also a fixed height and is not reducing. You have to apply transformations to it too.
Because if you're zooming in, the outside div adapts to the inside content, whereas if you're reducing it does not.

Categories