Test position fixed for iPhone

Testing position fixed for iphone can be a problem. If created the following script to test for position fixed. It seams to work, but please provide feedback in the comments.

var IOS_FIXED_POSITION;

window.onload = function () {

if (typeof document.body.scrollIntoViewIfNeeded === 'function') {

	(function () {
		var runTest = false,
		container = document.body,
		el = document.createElement('div'),
		originalHeight = container.style.height,
		originalScrollTop = window.pageYOffset;
		testScrollTop = 20;
		el.style.cssText = 'position:fixed;top:0px;height:10px;';

		container.appendChild(el);
		container.style.height="3000px";

		window.addEventListener('scroll', testScrollTop, false);
		window.setTimeout(testScroll, 20);
		window.scrollTo(0,testScrollTop );

		function testScroll() {
			if (IOS_FIXED_POSITION === undefined) {
				el.scrollIntoViewIfNeeded();
				if (window.pageYOffset === testScrollTop) {
					IOS_FIXED_POSITION = true;
				} else {
					IOS_FIXED_POSITION = false;
				}
			}
			window.removeEventListener('scroll', testScroll, false);
			container.style.height=originalHeight;
			container.removeChild(el);
			window.scrollTo(0,originalScrollTop);

		}

	}());
} else {
	IOS_FIXED_POSITION = false;
}
}

About Tor Brekke Skjøtskift

Senior Webdesigner Media Norge Digital
This entry was posted in CSS, Javascript. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>