Here's a couple of ways to ask this question:
How can I get the height (in pixels) at which the page will start having scroll bars? In other words, how do i get the window height at which a scroll bar will appear?
How can I get the maximum height of all elements on the page that don't have relative
heights (e.g. height: 100%)?
This question is related, but the answer doesn't do what I want in the case of relative heights: Finding the full height of the content of a page/document that can have absolutely positioned elements
I made a js fiddle of what I'm talking about: http://tinyurl.com/kgf8dae . Unfortunately, jsfiddle seems to break the relative height put on div e - run it as an html page in a normal browser to see the real behavior.
I might be misunderstand the question. In general, if the window height is less than the document height you will get a vertical scrollbar.
So in jQuery the check might look like this:
if( $(document).height() > $(window).height() ){ /* There will be a scrollbar */ }
You can perform this check within DOM changing and window resizing events to ascertain if a scrollbar has appeared. To preemptively determine if an event would cause a scrollbar to appear can be tricky and would likely require some understanding of the page and potential events to handle efficiently.
This is tagged through jQuery so I'm going to use jQuery; even though it's not mentioned in the question body.
a) It sounds like you want to get the height of the viewport (window); which can be retrieved like this:
var height = $(window).height();
If the height of the document (page) exceeds the height of the window, and there are no CSS properties blocking the display of scrollbars, then scrollbars will indeed by visible.
if( $(document).height() > $(window).height() )
b) This is going to be a bit trickier, in the sense the only way off the top of my head is to query every DOM element.. this is not a elegant solution; and in fact I'd ask you to reconsider your approach if you really you must do this. That said.. for curiosity...
If you're looking for the max height, in the sense of the largest element - then this would work:
// Get height of largest element.
var max_height = 0;
$('*').each( function(){
// skip <html> and <body>
if( ( $(this).get(0) == $('body').get(0) ) || ( $(this).get(0) == $('html').get(0) ) )
return;
var current_height = $(this).height();
if( current_height > max_height )
max_height = current_height;
});
For example, running that on this page...
> console.log( max_height );
570
However, I'm not sure if you want the maximum height of all combined elements.. In which case we obviously need to add all the elements up, but there's the obvious problem: elements are nested!
If this is what you want, then by using .children() we can just iterate through the lengths of the elements that are immediate children of your containing element/body.
// Get height of all combined elements
var combined_height = 0;
$('body').each( function(){ // replace with containing element?
combined_height = combined_height + jQuery(this).height();
});
For example, running that on this page:
> console.log(combined_height);
2176
Using the HTML/CSS from the example your provided via (jsfiddle.net/RMe3n/1). The answer is and always will be 242.
However, I assume you're looking for a more dynamic approach. Running the following after DOM ready will also produce 242:
var answer = 0;
$('#absolutes > div').each(function(){
var h = $(this).outerHeight(true);
if(answer < h) answer = h;
})
alert(answer);
While the above will solve for the particular HTML/CSS you provided it makes a lot of assumptions about the page's HTML structure and CSS.
Is it possible that the problem you are attempting to address with JS could be resolved in a "cleaner" way by adjusting the HTML/CSS of your page?
If you are looking for a fool proof JS method to account for ALL the multitude of unique layouts/styles that exist now and may exist as more CSS3 display types are adopted in the future I believe you're out of luck. There is no recommendable, consistent, efficient way to do so.
Note: If this is more than just a theoretical discussion, consider being more specific about the exact scenario you are faced with as there is likely a vastly different approach that may resolve the issue.
Related
Note that I'm not asking how to make a div the size of the "window" or "viewport" for which there are plenty of existing questions.
I have a web page of some height and width, and I'd like to add an empty, top-level div (i.e., not one containing the rest of the page) with a size exactly equal to the page's height and width. In practice, I also want it to be at least the size of the viewport.
I know I can do a one-time calculation of the height and width in JavaScript:
var height = Math.max(document.body.scrollHeight,
document.documentElement.clientHeight);
var width = Math.max(document.body.scrollWidth,
document.documentElement.clientWidth);
But this value can change based on images loading, or AJAX, or whatever other dynamic stuff is going on in the page. I'd like some way of locking the size of the div at the full page size so it resizes dynamically and on-demand.
I have tried something like the following:
function resetFakeBg() {
// Need to reset the fake background to notice if the page shrank.
fakeBg.style.height = 0;
fakeBg.style.width = 0;
// Get the full page size.
var pageHeight = Math.max(document.body.scrollHeight,
document.documentElement.clientHeight);
var pageWidth = Math.max(document.body.scrollWidth,
document.documentElement.clientWidth);
// Reset the fake background to the full page size.
fakeBg.style.height = pageHeight + 'px';
fakeBg.style.width = pageWidth + 'px';
}
// Create the fake background element.
fakeBg = setFakeBgStyle(document.createElement('div'));
document.body.appendChild(fakeBg);
// Keep resizing the fake background every second.
size_checker_interval = setInterval(resetFakeBg, 1000);
Limitations
This is for a Chrome extension, and I'd like to limit my modification of the page to adding this single div. This means that adding CSS to modify the height and width of the html and/or body tags is undesirable because it might have side-effects on the way the rest of the page is rendered.
In addition, I do not want to wrap the existing page in the div because that has the potential to break some websites. Imagine, for example, a site styled with the CSS selector body > div. I'd like my extension to break as few websites as possible.
WHY OH WHY WOULD I NEED TO DO THIS?
Because some people like to hold their answers hostage until they're satisfied that I have a Really Good Reason™ for wanting to do this:
This is for an accessibility-focused Chrome extension that applies a CSS filter across an entire page. Recent versions of Chrome (>= 45) do not apply CSS filters to backgrounds specified on the <html> or <body> tag. As a result, I have chosen to work around this limitation by copying the page's background onto a div with a very negative z-index value, so that it can be affected by the page-wide CSS filter. For this strategy to work, the div needs to exactly imitate the way the page background would appear to a user—by being the exact size of the document (and no larger) and at least filling the viewport.
setInterval() is your best friend in cases like this where you want the .height() and .width() of an element to be asynchronously specified all the time to something that can be dynamicly altered by user input and DOM tree changes. It is what I dub as a "page sniffer", and arguably, works better than $(document).ready if you are working in multiple languages (PHP, XML, JavaScript).
Working Example
You should get away with setting the width and height in the window resize function, you might wanna add it in a load function as well, when all data/images are loaded.
just add width=100%
e.g;-
Hello World
I think you must do it like this:
...
<body>
<script>
function height()
{var height = Math.max(document.body.scrollHeight,
document.documentElement.clientHeight);}
function width()
{var width = Math.max(document.body.scrollWidth,
document.documentElement.clientWidth);}
</script>
<div height="height()" width="width()">
</div>
</body>
...
I'm trying to work out the algorithm for a fixed div that grows in height (while scrolling) until it's equal to the height of the viewport or div with fixed position relative to another div and the bottom of the viewport
I am using Twitter Bootstrap affix to lock my secondary navigation bar (yellow) and my sidebar (black) to the top of the screen when the user scrolls that far.
This works fine. The sidebar is the piece that's giving me trouble. When it is in its in its starting position (as shown in the diagram belorw), I want the top of the bar to sit 30px
down from the secondary navigation bar (yellow) and 30px up from the bottom of the page.
As the user scrolls, the bar should grow in height so that it remains 30px beneath the secondary navigation bar and 30px above the bottom of the screen (As shown in the diagram below)
After the bar is fixed position, I am able to do what I need to do.
.sidebar {
position:fixed;
top:100px;
bottom:30px;
left:30px;
}
What I can't figure out is how to position the TOP of the sidebar relative to my
secondary navigation bar and the BOTTOM of my sidebar relative to the bottom
of the screen. I've tried calculating the height of the sidebar at the beginning and the end of the
scroll but this causes issues.
I've also tried calculating the final height of the sidebar and letting the bottom of
the sidebar just run off the edge of the screen (when it's in its initial position), but
if there's not enough content on the right side to warrant scrolling, I have no way
of getting to the bottom items in the scroll bar. Plus my screen starts bouncing
in a really unattractive way.
below is the current code in use:
ShelvesSideBar.prototype._resize_sidebar = function(_this) {
var PADDING = 50;
var window_height = $(window).height(),
nav_bar_height = $('.nav_bar').height() + $('.secondary_tabs').height(),
sidebar_height = window_height - nav_bar_height - PADDING,
sidebar_scrollable_height = sidebar_height - $('.bar_top').height();
_this.$container.height(sidebar_height);
_this.$container.find('.bar_bottom').height(sidebar_scrollable_height);
/* reset the nanoscroller */
_this.$container.nanoScroller();
};
this code is called on page load and again on window resize. Any help would be greatly appreciated!
I've been trying to do something similar (minus the fixed elements and navbars). What I found was in order to do any sort of relative height scaling every element above the element I wished to scale all the way up to the opening html tags had to have a relative height set, even if it was just height:100%;. (here's my original question Variable height, scrollable div, contents floating)
My goal was to have the body height fixed to window size like a native full screen application would be with my content subareas scrolling, so this is a bit off topic for what you're wanting to accomplish. But I tried using JS/JQ to start off with as you're trying to do currently and found that I simply couldn't get the window height because the default behaviour for height management is to expand the page height until everything on the page fits. And all the getHeight methods I tried we're getting the page height not window/viewport height as promised. So you may wish to try fixing your body's height to the window and going from there using overflow:scroll; to scroll the page.
A quick note on overflow:scroll; if you have users who use WP8 IE (and probably other versions of IE) it may be advantageous to implement FTscroller to handle all your scroll elements as the overflow property defaults to hidden and is a fixed browser property. The only problem with FTscroller is because it uses CSS offsets to move the content container it may wreak havoc on elements that are designed to switched to fix when they reach x height from top of page because technically the top of page (or rather the top of the container they're in) isn't at the top of the page anymore it's beyond it. Just something to be aware of if you do need to cater for this browser.
And apologies for the complexity of my sentence structure. :/
so I was able to figure this out, for anyone still looking. What I ended up doing was binding to the window scroll event and - whenever the scroll occurred - I check if the class "affix" has been added to the sidebar. If it has, then I perform one set of calculations to determine sidebar height. Otherwise, I perform the other set of calculations. Code below:
/* called on window scroll */
var PADDING = 70;
var window_height = $(window).height(),
nav_bar_height = $('.nav_bar').height() + $('.secondary_tabs').height(),
header_height = $('.prof_block').height() - nav_bar_height,
sidebar_height = _this.$container.hasClass("affix") ? window_height - nav_bar_height - PADDING : window_height - (header_height + nav_bar_height) - PADDING,
sidebar_scrollable_height = sidebar_height - $('.bar_top').height();
_this.$container.height(sidebar_height);
_this.$container.find('.bar_bottom').height(sidebar_scrollable_height);
Is there any way to know if an element is visible on an html page?
Like this:
One can probably do it considering the horizontal/vertical scrolling positions, the width/height of the browser window and the position/size of the element on the page, but I have little experience in jQuery so I don't know how to do it. And there might be a simple function one can call, I don't know.
You can use the .is(':visible') selectors to check if an element is currently visible in the DOM.
Edit:
However, as #BenM mentioned, this doesn't check if the elements on your page are actually out of your scrollable range - a great little plugin you could use in that case would be Viewport Selectors for jQuery.
Here is some code that I use to do this. It has been tested to work great.
function isVisible($obj) {
var top = $(window).scrollTop();
var bottom = top + $(window).height();
var objTop = $obj.offset().top;
var objBottom = objTop + $obj.height();
if(objTop < bottom && objBottom > top) {
//some part of $obj is visible on the screen.
//does not consider left/right, only vertical.
}
}
I have a control contained in an iframe on a page of my ASP.NET web application.
Control changes its vertical size correspondingly to what user selects on it (some elements get in, others get out). So, I have to set the iframe size precisely to get the whole control shown and not to make gap between the iframe and the elements below it.
Somewhere on the web I have found a way to get the document height in a cross-browser way:
function getDocHeight(document) {
return Math.max(
Math.max(document.body.scrollHeight, document.documentElement.scrollHeight),
Math.max(document.body.offsetHeight, document.documentElement.offsetHeight),
Math.max(document.body.clientHeight, document.documentElement.clientHeight)
);
}
On self.document.body.onload on the control page, hence, I call this function:
function adjustIframeHeight() {
var iframe = window.parent.document.getElementById(window.frameElement.id);
var iframeHeight = getDocHeight(iframe.contentWindow.document);
iframe.style.height = iframeHeight + "px";
}
The problem is it works fine e.g. in Firefox, but in some cases bottom sections of the control are cutoff in Chrome and IE for example.
Is there some truly cross-browser way to get this height, or I am doing something else wrong?
Thank you for the time
I'd use something like jQuery to help out with this (since using height methods seem to vary from browser to browser) and here is some jQuery code that could help out:
$(document).height(); // height of HTML doc
I'm trying to counteract an adjustment to the height of an element which is above the scroll offset by calculating the difference in height and then updating the current scroll position to account for it.
The problem is that there's no way that I can prevent a very quick flickering artefact. Whether I adjust the element's height and then the scroll position, or vice versa, I can't seem to prevent a quick visual jump.
Does anyone know how this could be overcome? I want these to operations to happen at the same time with no rendering in-between but I'm not sure if it's possible.
// Setup
...
var myElement = ...
var oldHeight = ...
var scrollOffset = window.scrollY;
var newHeight = 100;
var diff = newHeight - oldHeight;
// Determine if we need to counteract new size
var adjustScroll = (absoluteOffset(myElement) < scrollOffset);
// Adjust size
myElement.style.height = newHeight+'px';
// Adjust scroll to counteract the new height
if (adjustScroll) window.scrollTo(0, scrollOffset+diff);
I'm working with WebKit, specifically on iOS.
for webkit you can use CSS transitions/animations to smooth this but it's still sound like you are going the wrong way to begin with. I am sure that whatever is it you are trying to do can be solved purely with CSS (maybe with some very minimal Javaqscript). Post an example of you HTML + CSS + JS.
You could use scrollIntoView with timers to simulate multiple threads.
Or you could do it inside a document fragment beforehand.
Sorry to be reviving an old post here, but i came across this looking for a solution to a similar problem to do with browser resizing.
Stackoverflow user James Kyle created this little jsfiddle using jQuery that attempts to maintain scroll position as best as possible when a page is resized
var html = $('html'),
H = html.outerHeight(true),
S = $(window).scrollTop(),
P = S/H;
$(window).scroll(function() {
S = $(window).scrollTop();
P = S/H;
});
$(window).resize(function() {
H = html.outerHeight(true);
$(window).scrollTop(P*H);
});
http://jsfiddle.net/JamesKyle/RmNap/
you could try using this same code and trigger a 'resize' event on the html when the image has loaded by using a jQuery library like imagesLoaded