Reputation: 22257
Is there any reliable method to detect if the browser supports position fixed
?
I've found some solutions but none of them seems to work well on all browsers.
Upvotes: 7
Views: 5230
Reputation: 33408
var supportFixed = (function () {
var elem = document.createElement('div');
elem.style.cssText = 'position:fixed';
if (elem.style.position.match('fixed')) return true;
return false;
}());
Upvotes: 2
Reputation: 1617
While developing a mobile application with jQuery Mobile I had the same problem. The headers should have fixed position (if supported by the browser) and the solution was to set the headers with a default position: fixed
on the css and checked the supported property through the following method:
function isPositionFixedSupported() {
return $( '[data-role="header"]' ).css( 'position' ) === 'fixed';
}
The returned value is static
if not supported by the browser.
Upvotes: 9
Reputation: 3171
Does something like this work on mobile browsers?
function isFixedPositionSupported() {
var e = document.createElement('div')
try {
e.style.position = 'fixed'
return e.style.position == 'fixed'
} catch (exception) {
return false
}
}
Upvotes: 1
Reputation: 692
Ohgodwhy's code is correct, but for iOS, you can check the user agent and see if it's the iOS Safari. Then return that it is supported. The user agent strings are
Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3
Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3
Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7
I'm not sure how to code this, but I'm sure this is what you need to do to detect iOS.
Upvotes: -1
Reputation: 50787
This code works completely fine. Just tested it on a Windows ME box with IE6, returns 'null' because IE6 doesn't support position:fixed;
.
by the way, this is NOT originally my code. ALL credits go to Kangax's Github who has many functions there to test browser features.
function () {
var container = document.body;
if (document.createElement &&
container && container.appendChild && container.removeChild) {
var el = document.createElement("div");
if (!el.getBoundingClientRect) {
return null;
}
el.innerHTML = "x";
el.style.cssText = "position:fixed;top:100px;";
container.appendChild(el);
var originalHeight = container.style.height, originalScrollTop = container.scrollTop;
container.style.height = "3000px";
container.scrollTop = 500;
var elementTop = el.getBoundingClientRect().top;
container.style.height = originalHeight;
var isSupported = elementTop === 100;
container.removeChild(el);
container.scrollTop = originalScrollTop;
return isSupported;
}
return null;
}
If it runs, it works, if it doesn't, you'll get a null.
Upvotes: 3