Free-Scrolling Sticky Sidebar Without jQuery - javascript

I'm trying to achieve what is outlined in this Stack Overflow question, without jQuery dependency: stackoverflow.com/questions/18358816/sticky-sidebar-stick-to-bottom-when-scrolling-down-top-when-scrolling-up
But I didn't want to hijack that question.
Basically, I want the content in the sidebar to be independently scrollable but fixed when the viewport reaches either end of the sidebars contents on scroll.
My main stumbling block appears to not being able to calculate the elementTop variable when the sidebar is absolutely positioned and between the top and bottom of the container which I have set to be full height.
Full code below:
var StickySidebar = function(eventie) {
var container, containerTop, containerHeight, // container
element, elementTop, elementHeight, elStyle, // element
viewportTop = -1, viewportHeight, documentTop, // viewport
lastViewportTop, scrollingDown, top = false , bottom = false,// sticky vars
scroll = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame ||
function(callback){ window.setTimeout(callback, 1000/60); },
options = {
container : document.querySelector('.sidebar-container'),
element : document.querySelector('.sidebar'),
sidebarClass : 'sidebar',
bottomOffset : -15,
topOffset: 90,
},
_updateValue = function() {
viewportHeight = window.innerHeight;
},
_offset = function(obj) {
var ol = ot = 0;
if (obj.offsetParent) {
do {
ol += obj.offsetLeft;
ot += obj.offsetTop;
} while (obj = obj.offsetParent);
}
return {
left: ol,
top: ot
};
},
init = function(){
if(options.element !== null) {
container = options.container;
containerTop = offset(container).top;
containerHeight = container.clientHeight;
element = options.element;
elementTop = offset(element).top;
elementHeight = options.element.clientHeight;
lastViewportTop = window.scrollY;
viewportHeight = window.innerHeight;
eventie.bind(document, "scroll", _loop);
eventie.bind(window, "resize", _updateValue);
}
},
_loop = function() {
if (viewportTop == window.pageYOffset) {
scroll(_loop);
return false;
} else viewportTop = window.pageYOffset;
_updateValue();
var viewportBottom, elementTooBig, topOffset;
elementTop = offset(element).top;
elementHeight = element.clientHeight;
containerHeight = container.clientHeight;
scrollingDown = viewportTop > lastViewportTop;
elementTooBig = elementHeight > viewportHeight;
console.log("elementTop : " + elementTop);
console.log("viewportTop : " + viewportTop);
if (scrollingDown) {
if (viewportTop + viewportHeight >= elementTop + elementHeight) {
element.setAttribute('style','position:fixed; bottom:30px;');
} else {
element.setAttribute('style','position:absolute; top:'+ elementTop +'px;'); // issue 1
}
if (viewportTop + viewportHeight > containerTop + containerHeight) {
element.setAttribute('style','position:absolute; bottom:0;');
}
} else {
if (viewportTop < containerTop - 60) {
element.removeAttribute('style');
return;
}
if (viewportTop <= elementTop) {
element.setAttribute('style','position:fixed; top:90px;');
} else {
element.setAttribute('style','position:absolute; top:'+ elementTop +'px;');
elementTop = viewportTop + elementTop;
}
}
lastViewportTop = viewportTop;
};
return {
init: init
};
}(eventie);
I've been trying to tackle this issue for a few weeks now, and it has been driving me insane. Any help would be greatly appreciated.

If you're just trying to achieve the desired result not necessarily creating that yourself - well, there are many JavaScript libraries that provide that.
For example, Stickyfill is actually a polyfill for position: sticky which is natively supported only in Firefox 41+ and Safari 8+. Here is the demo with all kinds of stickiness you can imagine :)
P.S. At first glance you might notice something about jQuery there, but it's pure JavaScript and just adds a jQuery extension.

Related

How to remove jank when setting an element to a fixed position using JavaScript

I have a webpage that when scrolled down, the text freezes when it reaches the last paragraph of text but the images keep on scrolling. I've got the implementation working but there is a lot of jank when scrolling with a mouse wheel, not so much if I click and drag the scroll bar.
Are there any optimizations I can make to this code to make work as intended or is there a different way to accomplish the same task?
window.addEventListener('scroll', function (e) {
window.requestAnimationFrame(keepTextStationary);
//keepTextStationary(); // Less janky, but still horrible
});
function keepTextStationary() {
var textRect = writtenContent.getBoundingClientRect();
var imageRec = images.getBoundingClientRect();
if (textRect.bottom < window.innerHeight && document.documentElement.scrollTop > 0) {
writtenContent.style.position = 'relative';
writtenContent.style.bottom = (225 - document.documentElement.scrollTop) + 'px';
if (imagesTop === undefined) {
imagesTop = imageRec.y;
}
} else {
writtenContent.style.bottom = (225 - document.documentElement.scrollTop) + 'px';
}
if (imageRec.y >= imagesTop) {
writtenContent.style.position = '';
}
}
Here is the site so you can see the problem.
https://bowerbankninow.azurewebsites.net/exhibitions/oscar-perry-the-pheasant
You are causing layout trashing every time you call getBoundingClientRect. Try debouncing your scroll events:
var lastScrollY = 0;
var ticking = false;
function keepTextStationary() {
var textRect = writtenContent.getBoundingClientRect();
var imageRec = images.getBoundingClientRect();
if (textRect.bottom < window.innerHeight && lastScrollY > 0) {
writtenContent.style.position = 'relative';
writtenContent.style.bottom = (225 - lastScrollY) + 'px';
if (imagesTop === undefined) {
imagesTop = imageRec.y;
}
} else {
writtenContent.style.bottom = (225 - lastScrollY) + 'px';
}
if (imageRec.y >= imagesTop) {
writtenContent.style.position = '';
}
ticking = false;
}
function onScroll() {
lastScrollY = document.documentElement.scrollTop;
requestTick();
}
function requestTick() {
if (!ticking) {
requestAnimationFrame(keepTextStationary);
ticking = true;
}
}
window.addEventListener('scroll', onScroll );
See this article for in-depth explanation: https://www.html5rocks.com/en/tutorials/speed/animations/
You dont.
Relocations / styling in javascript take place after the CSS has been loaded. Bad practise. What you can do, is make it animated to make it look less horrible.
Why is pure CSS not an option ?

How to stop a fixed gadget before the footer?

everyone! Searching the internet for solutions related to stick a widget in the sidebar I've found one that I liked. But, the only problem is that it doesn't "break" before the footer. I've already tried a lot of solutions, but without sucess until now. If someone can help me, I thank!
This is the original script:
<script type='text/javascript'>
/*<![CDATA[*/
// Sticky Plugin
// =============
// Author: Anthony Garand
// Improvements by German M. Bravo (Kronuz) and Ruud Kamphuis (ruudk)
// Created: 2/14/2011
// Date: 9/12/2011
// Website: http://labs.anthonygarand.com/sticky
// Description: Makes an element on the page stick on the screen as you scroll
// For Blogger by : http://www.makingdifferent.com
(function($) {
var defaults = {
topSpacing: 0,
bottomSpacing: 0,
className: 'is-sticky',
center: false
},
$window = $(window),
$document = $(document),
sticked = [],
windowHeight = $window.height(),
scroller = function() {
var scrollTop = $window.scrollTop(),
documentHeight = $document.height(),
dwh = documentHeight - windowHeight,
extra = (scrollTop > dwh) ? dwh - scrollTop : 0;
for (var i = 0; i < sticked.length; i++) {
var s = sticked[i],
elementTop = s.stickyWrapper.offset().top,
etse = elementTop - s.topSpacing - extra;
if (scrollTop <= etse) {
if (s.currentTop !== null) {
s.stickyElement.css('position', '').css('top', '').removeClass(s.className);
s.currentTop = null;
}
}
else {
var newTop = documentHeight - s.elementHeight - s.topSpacing - s.bottomSpacing - scrollTop - extra;
if (newTop < 0) {
newTop = newTop + s.topSpacing;
} else {
newTop = s.topSpacing;
}
if (s.currentTop != newTop) {
s.stickyElement.css('position', 'fixed').css('top', newTop).addClass(s.className);
s.currentTop = newTop;
}
}
}
},
resizer = function() {
windowHeight = $window.height();
};
// should be more efficient than using $window.scroll(scroller) and $window.resize(resizer):
if (window.addEventListener) {
window.addEventListener('scroll', scroller, false);
window.addEventListener('resize', resizer, false);
} else if (window.attachEvent) {
window.attachEvent('onscroll', scroller);
window.attachEvent('onresize', resizer);
}
$.fn.sticky = function(options) {
var o = $.extend(defaults, options);
return this.each(function() {
var stickyElement = $(this);
if (o.center)
var centerElement = "margin-left:auto;margin-right:auto;";
stickyId = stickyElement.attr('id');
stickyElement
.wrapAll('<div id="' + stickyId + 'StickyWrapper" style="' + centerElement + '"></div>')
.css('width', stickyElement.width());
var elementHeight = stickyElement.outerHeight(),
stickyWrapper = stickyElement.parent();
stickyWrapper
.css('width', stickyElement.outerWidth())
.css('height', elementHeight)
.css('clear', stickyElement.css('clear'));
sticked.push({
topSpacing: o.topSpacing,
bottomSpacing: o.bottomSpacing,
stickyElement: stickyElement,
currentTop: null,
stickyWrapper: stickyWrapper,
elementHeight: elementHeight,
className: o.className
});
});
};
})(jQuery);
/*]]>*/
</script>

Calculating & setting scroll speed of object in viewport

I have image I am scrolling within a div.
It make sure the image is visible I am using
var isVisible = (
threshold.top >= -39 &&
threshold.bottom <= (window.innerHeight || document.documentElement.clientHeight)
);
What I am trying to do now is make sure that once the element is visible it is able to completely finish scrolling before going out of the view port.
I am thinking I can do this by effecting the speed value based on the the distance of the element from the top on the window. But I am having a very hard time doing this.
I am using .getBoundingClientRect() to get the distance the element is from the top of the viewport:
var threshold = document.getElementById('page-feature').getBoundingClientRect();
var thresholdY = threshold.top;
Below is my code so far:
function scrollImageInViewport() {
var threshold = document.getElementById('page-feature').getBoundingClientRect();
var thresholdY = threshold.top;
var isVisible = (
threshold.top >= -39 &&
threshold.bottom <= (window.innerHeight || document.documentElement.clientHeight)
);
if (isVisible && window.innerWidth > 550) {
scrollDir(thresholdY);
}
}
function scrollUp(thresholdY) {
if (thresholdCounter < maxScrollNegative) {
return;
} else {
pageScroll.setAttribute('style', '-webkit-transform:translate3d(0,' + (--thresholdCounter *speed) + 'px,0); -ms-transform:translate3d(0,' + (--thresholdCounter *speed) + 'px,0); transform:translate3d(0,' + (--thresholdCounter *speed) + 'px,0);');
}
};
function scrollDown(thresholdY) {
if (thresholdCounter > maxScrollPositive) {
return;
} else {
pageScroll.setAttribute('style', '-webkit-transform:translate3d(0,' + (++thresholdCounter *speed) + 'px,0); -ms-transform:translate3d(0,' + (++thresholdCounter *speed) + 'px,0); transform:translate3d(0,' + (++thresholdCounter *speed) + 'px,0);');
}
};
function scrollToTop(){
initScroll();
pageScroll.setAttribute('style', 'transform:translate3d(0,0,0);');
thresholdCounter = 0;
};
function scrollDir(thresholdY) {
var scroll = window.scrollY;
if(scroll > position) {
distanceFromTop(thresholdY);
scrollUp(thresholdY);
} else if (scroll < position ){
scrollDown(thresholdY);
}
position = scroll;
};
function distanceFromTop(thresholdY) {
if (thresholdY > 0) {
`enter code here`//set speed as distance from top /px of not shown content
speed = (scrollImageHeight - scrollVisibleHeight) / thresholdY;
}
};
function initScroll(){
position = window.scrollY;
pageScroll = document.getElementById('page-scroll');
scrollImageHeight = pageScroll.offsetHeight; //total height of scroll image
pagePanel = document.getElementById("pagePanel");
pageStyle = window.getComputedStyle(pagePanel,"");
size = pageStyle.getPropertyValue("height");
scrollVisibleHeight = parseInt(size, 10);//visible height of scroll image
scrollImageEnd = scrollImageHeight - scrollVisibleHeight;
maxScrollNegative = -scrollImageEnd / speed;
}
var speed;
var thresholdCounter = 0;
var maxScrollPositive = 0;
var position,
pageScroll,
scrollImageHeight,
pagePanel,
pageStyle,
size,
scrollVisibleHeight,
scrollImageEnd,
maxScrollNegative;
window.addEventListener('resize', scrollToTop);
document.addEventListener('scroll', scrollImageInViewport);
window.addEventListener('load', initScroll);
This is what I ended up with:
var featurePage = document.getElementById('page-feature')
var pageScroll = document.getElementById('page-scroll');
var startP, // where animation needs to begin
endP, // where animation needs to end
diff; // visible element size
function getElementOffset(){ //init
var de = document.documentElement;
var box = featurePage.getBoundingClientRect();
var top = box.top + window.pageYOffset - de.clientTop;
var bottom = box.bottom + window.pageYOffset - de.clientTop;
var winHight = window.innerHeight;
diff = bottom - top;
var elPadding = (winHight - diff);
startP = top - elPadding;
endP = bottom - elPadding;
scrollImage()
}
function scrollImage(){
var scrollImageHeight = pageScroll.offsetHeight;
var scrollPos = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
var s1 = scrollPos - startP;
var realPos = -s1/diff;
var lengthLeft = scrollImageHeight - (diff)
if ( realPos < 0.09 && realPos > -1){
pageScroll.setAttribute('style', '-webkit-transform:translate3d(0,' + (realPos * lengthLeft) + 'px,0); -ms-transform:translate3d(0,' + (realPos *lengthLeft) + 'px,0); transform:translate3d(0,' + (realPos *lengthLeft) + 'px,0);');
}
}
window.addEventListener('resize', getElementOffset);
document.addEventListener('scroll', getElementOffset);

Scroll if element is not visible

how to determine, using jquery, if the element is visible on the current page view. I'd like to add a comment functionality, which works like in facebook, where you only scroll to element if it's not currently visible. By visible, I mean that it is not in the current page view, but you can scroll to the element.
Live Demo
Basically you just check the position of the element to see if its within the windows viewport.
function checkIfInView(element){
var offset = element.offset().top - $(window).scrollTop();
if(offset > window.innerHeight){
// Not in view so scroll to it
$('html,body').animate({scrollTop: offset}, 1000);
return false;
}
return true;
}
Improving Loktar's answer, fixing the following:
Scroll up
Scroll to a display:none element (like hidden div's etc)
function scrollToView(element){
var offset = element.offset().top;
if(!element.is(":visible")) {
element.css({"visibility":"hidden"}).show();
var offset = element.offset().top;
element.css({"visibility":"", "display":""});
}
var visible_area_start = $(window).scrollTop();
var visible_area_end = visible_area_start + window.innerHeight;
if(offset < visible_area_start || offset > visible_area_end){
// Not in view so scroll to it
$('html,body').animate({scrollTop: offset - window.innerHeight/3}, 1000);
return false;
}
return true;
}
After trying all these solutions and many more besides, none of them satisfied my requirement for running old web portal software (10 years old) inside IE11 (in some compatibility mode). They all failed to correctly determine if the element was visible. However I found this solution. I hope it helps.
function scrollIntoViewIfOutOfView(el) {
var topOfPage = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
var heightOfPage = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
var elY = 0;
var elH = 0;
if (document.layers) { // NS4
elY = el.y;
elH = el.height;
}
else {
for(var p=el; p&&p.tagName!='BODY'; p=p.offsetParent){
elY += p.offsetTop;
}
elH = el.offsetHeight;
}
if ((topOfPage + heightOfPage) < (elY + elH)) {
el.scrollIntoView(false);
}
else if (elY < topOfPage) {
el.scrollIntoView(true);
}
}
I made a slightly more generic version of digitalPBK's answer that minimally scrolls an element contained within a div or some other container (including the body). You can pass DOM elements or selectors to the function, as long as the element is somehow contained within the parent.
function scrollToView(element, parent) {
element = $(element);
parent = $(parent);
var offset = element.offset().top + parent.scrollTop();
var height = element.innerHeight();
var offset_end = offset + height;
if (!element.is(":visible")) {
element.css({"visibility":"hidden"}).show();
var offset = element.offset().top;
element.css({"visibility":"", "display":""});
}
var visible_area_start = parent.scrollTop();
var visible_area_end = visible_area_start + parent.innerHeight();
if (offset-height < visible_area_start) {
parent.animate({scrollTop: offset-height}, 600);
return false;
} else if (offset_end > visible_area_end) {
parent.animate({scrollTop: parent.scrollTop()+ offset_end - visible_area_end }, 600);
return false;
}
return true;
}
You can take a look at his awesome link from the jQuery Cookbook:
Determining Whether an Element Is Within the Viewport
Test if Element is contained in the Viewport
jQuery(document).ready(function() {
var viewportWidth = jQuery(window).width(),
viewportHeight = jQuery(window).height(),
documentScrollTop = jQuery(document).scrollTop(),
documentScrollLeft = jQuery(document).scrollLeft(),
$myElement = jQuery('#myElement'),
elementOffset = $myElement.offset(),
elementHeight = $myElement.height(),
elementWidth = $myElement.width(),
minTop = documentScrollTop,
maxTop = documentScrollTop + viewportHeight,
minLeft = documentScrollLeft,
maxLeft = documentScrollLeft + viewportWidth;
if (
(elementOffset.top > minTop && elementOffset.top + elementHeight < maxTop) &&
(elementOffset.left > minLeft && elementOffset.left + elementWidth < maxLeft)
) {
alert('entire element is visible');
} else {
alert('entire element is not visible');
}
});
Test how much of the element is visible
jQuery(document).ready(function() {
var viewportWidth = jQuery(window).width(),
viewportHeight = jQuery(window).height(),
documentScrollTop = jQuery(document).scrollTop(),
documentScrollLeft = jQuery(document).scrollLeft(),
$myElement = jQuery('#myElement'),
verticalVisible, horizontalVisible,
elementOffset = $myElement.offset(),
elementHeight = $myElement.height(),
elementWidth = $myElement.width(),
minTop = documentScrollTop,
maxTop = documentScrollTop + viewportHeight,
minLeft = documentScrollLeft,
maxLeft = documentScrollLeft + viewportWidth;
function scrollToPosition(position) {
jQuery('html,body').animate({
scrollTop : position.top,
scrollLeft : position.left
}, 300);
}
if (
((elementOffset.top > minTop && elementOffset.top < maxTop) ||
(elementOffset.top + elementHeight > minTop && elementOffset.top +
elementHeight < maxTop))
&& ((elementOffset.left > minLeft && elementOffset.left < maxLeft) ||
(elementOffset.left + elementWidth > minLeft && elementOffset.left +
elementWidth < maxLeft)))
{
alert('some portion of the element is visible');
if (elementOffset.top >= minTop && elementOffset.top + elementHeight
<= maxTop) {
verticalVisible = elementHeight;
} else if (elementOffset.top < minTop) {
verticalVisible = elementHeight - (minTop - elementOffset.top);
} else {
verticalVisible = maxTop - elementOffset.top;
}
if (elementOffset.left >= minLeft && elementOffset.left + elementWidth
<= maxLeft) {
horizontalVisible = elementWidth;
} else if (elementOffset.left < minLeft) {
horizontalVisible = elementWidth - (minLeft - elementOffset.left);
} else {
horizontalVisible = maxLeft - elementOffset.left;
}
var percentVerticalVisible = (verticalVisible / elementHeight) * 100;
var percentHorizontalVisible = (horizontalVisible / elementWidth) * 100;
if (percentVerticalVisible < 50 || percentHorizontalVisible < 50) {
alert('less than 50% of element visible; scrolling');
scrollToPosition(elementOffset);
} else {
alert('enough of the element is visible that there is no need to scroll');
}
} else {
// element is not visible; scroll to it
alert('element is not visible; scrolling');
scrollToPosition(elementOffset);
}
The following code helped me achieve the result
function scroll_to_element_if_not_inside_view(element){
if($(window).scrollTop() > element.offset().top){
$('html, body').animate( { scrollTop: element.offset().top }, {duration: 400 } );
}
}
Here is the solution I came up with, working both up and down and using only Vanilla Javascript, no jQuery.
function scrollToIfNotVisible(element) {
const rect = element.getBoundingClientRect();
// Eventually an offset corresponding to the height of a fixed navbar for example.
const offset = 70;
let scroll = false;
if (rect.top < offset) {
scroll = true;
}
if (rect.top > window.innerHeight) {
scroll = true;
}
if (scroll) {
window.scrollTo({
top: (window.scrollY + rect.top) - offset,
behavior: 'smooth'
})
}
}
There is a jQuery plugin which allows us to quickly check if a whole element (or also only part of it) is within the browsers visual viewport regardless of the window scroll position. You need to download it from its GitHub repository:
Suppose to have the following HTML and you want to alert when footer is visible:
<section id="container">
<aside id="sidebar">
<p>
Scroll up and down to alert the footer visibility by color:
</p>
<ul>
<li><span class="blue">Blue</span> = footer <u>not visible</u>;</li>
<li><span class="yellow">Yellow</span> = footer <u>visible</u>;</li>
</ul>
<span id="alert"></span>
</aside>
<section id="main_content"></section>
</section>
<footer id="page_footer"></footer>
So, add the plugin before the close of body tag:
<script type="text/javascript" src="js/jquery-1.12.0.min.js"></script>
<script type="text/javascript" src="js/jquery_visible/examples/js/jq.visible.js"></script>
After that you can use it in a simple way like this:
<script type="text/javascript">
jQuery( document ).ready(function ( $ ) {
if ($("footer#page_footer").visible(true, false, "both")) {
$("#main_content").css({"background-color":"#ffeb3b"});
$("span#alert").html("Footer visible");
} else {
$("#main_content").css({"background-color":"#4aafba"});
$("span#alert").html("Footer not visible");
}
$(window).scroll(function() {
if ($("footer#page_footer").visible(true, false, "both")) {
$("#main_content").css({"background-color":"#ffeb3b"});
$("span#alert").html("Footer visible");
} else {
$("#main_content").css({"background-color":"#4aafba"});
$("span#alert").html("Footer not visible");
}
});
});
</script>
Here a demo
No-JQuery version.
The particular case here is where the scroll container is the body (TBODY, table.body) of a TABLE (scrolling independently of THEAD). But it could be adapted to any situation, some simpler.
const row = table.body.children[ ... ];
...
const bottomOfRow = row.offsetHeight + row.offsetTop ;
// if the bottom of the row is in the viewport...
if( bottomOfRow - table.body.scrollTop < table.body.clientHeight ){
// ... if the top of the row is in the viewport
if( row.offsetTop - table.body.scrollTop > 0 ){
console.log( 'row is entirely visible' );
}
else if( row.offsetTop - table.body.scrollTop + row.offsetHeight > 0 ){
console.log( 'row is partly visible at top')
row.scrollIntoView();
}
else {
console.log( 'top of row out of view above viewport')
row.scrollIntoView();
}
}
else if( row.offsetTop - table.body.scrollTop < table.body.clientHeight ){
console.log( 'row is partly visible at bottom')
row.scrollIntoView();
}
else {
console.log( 'row is out of view beneath viewport')
row.scrollIntoView();
}
I think this is the complete answer. An elevator must be able to go both up and down ;)
function ensureVisible(elementId, top = 0 /* set to "top-nav" Height (if you have)*/) {
let elem = $('#elementId');
if (elem) {
let offset = elem.offset().top - $(window).scrollTop();
if (offset > window.innerHeight) { // Not in view
$('html,body').animate({ scrollTop: offset + top }, 1000);
} else if (offset < top) { // Should go to top
$('html,body').animate({ scrollTop: $(window).scrollTop() - (top - offset) }, 1000);
}
}
}

Make javascript-snippet affect 3 divs instead of 1

I have this very usefull little piece of javascript that centers mig div. By i would like to make it apply to 3 divs on the same site, without repeating the same piece of code 3 times.
Any ideas on how to do it?
Putting all 3 divs into 1 divs that takes care of it, is not and option.
<script type="text/javascript">
<!--
function getWindowHeight() {
var windowHeight = 0;
if (typeof(window.innerHeight) == 'number') {
windowHeight = window.innerHeight;
}
else {
if (document.documentElement && document.documentElement.clientHeight) {
windowHeight = document.documentElement.clientHeight;
}
else {
if (document.body && document.body.clientHeight) {
windowHeight = document.body.clientHeight;
}
}
}
return windowHeight;
}
function setContent() {
if (document.getElementById) {
var windowHeight = getWindowHeight();
if (windowHeight > 0) {
var contentElement = document.getElementById('outer');
var contentHeight = contentElement.offsetHeight;
if (windowHeight < 570) {
contentElement.style.position = 'relative';
contentElement.style.top = '30px';
}
else if (windowHeight - contentHeight > 0) {
contentElement.style.position = 'relative';
contentElement.style.top = ((windowHeight / 2) - (contentHeight / 2)) + 'px';
}
else {
contentElement.style.position = 'static';
}
}
}
}
window.onload = function() {
setContent();
}
window.onresize = function() {
setContent();
}
//-->
</script>
Regards Troels
You don't need to check if document.getElementById exists. It has been supported since the Roman Empire.
Pass the id or the actual element that has to be centered to your function. That removes the dependency on a fixed element (#outer) in your case and makes it more flexible. Also try to name your functions to be indicative of what they are actually doing. setContent is a very generic name and doesn't indicate the centering aspect anywhere.
function centerElementWithId(id) {
..
var contentElement = document.getElementById(id);
..
}
Then call it thrice,
centerElementWithId('outer')
centerElementWithId('secondDiv')
centerElementWithId('thirdDiv');

Categories

Resources