Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery check if browser support position: fixed

How do I check if browser supports position:fixed using jQuery. I assume I have to use $.support I think, but how?

Thank you for your time.

like image 857
Alec Smart Avatar asked Jun 10 '09 05:06

Alec Smart


2 Answers

The most reliable way would be to actually feature-test it. Browser sniffing is fragile and unreliable.

I have an example of such test in CFT http://kangax.github.com/cft/#IS_POSITION_FIXED_SUPPORTED. Note that the test should be run after document.body is loaded.

like image 131
kangax Avatar answered Oct 04 '22 13:10

kangax


I find that mobile safari (specifically iOS 4.2 via the iOS Simulator on OSX) refuses to scroll anywhere unless you wait a few miliseconds. Hence the false positive.

I wrote a quick jquery plugin to work around it:

(function($) {
  $.support.fixedPosition = function (callback) {
    setTimeout(
      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;
          callback(isSupported);
        }
        else {
          callback(null);
        }
      }, 
      20
    );
  }
})(jQuery);
like image 34
user835325 Avatar answered Oct 04 '22 13:10

user835325