Correct offset values in jQuery on the iPad
- 14 February, 2011 -
- Client-side -
- Tags : ipad, jquery, mobile, snippet
- 0 Comments
Using the jQuery offset() method results in unreliable values being returned on the native iPad Safari mobile browser. More details about the issue have been posted in this ticket at the jQuery bug tracker. In the comments there, I noticed a solution posted by “matas”, which helped me to circumvent this issue in an application I was designing. It simply overwrites the offset() method with a corrected one, in case mobile Safari is detected as the user agent. Worked perfectly for me! The original code of matas can be found at Gist by GitHub.
Don’t overtake the code straightaway which was posted by matas originally, since this also affects the iPhone, where the offset() works properly. I’ve updated my implementation below to specifically check for an iPad instead of the more generic mobile Safari.
// as of 1.4.2 the mobile safari reports wrong values on offset()
// http://dev.jquery.com/ticket/6446
// remove once it's fixed
if((navigator.userAgent.match(/iPad/i))) {
(function($) {
$.fn.offsetOld = $.fn.offset;
$.fn.offset = function() {
var result = this.offsetOld();
result.top -= window.scrollY;
result.left -= window.scrollX;
return result;
};
})(jQuery);
}