From cf672a2e7a886cac5ae62f6772c6b4b43b19a2fc Mon Sep 17 00:00:00 2001 From: John Resig Date: Tue, 28 Sep 2010 10:55:48 -0400 Subject: [PATCH] Make sure that .offset() doesn't fail against disconnected DOM nodes. Fixes #4996. --- src/offset.js | 12 +++++++++--- test/unit/offset.js | 9 +++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/src/offset.js b/src/offset.js index 650cc08e9..39763ee60 100644 --- a/src/offset.js +++ b/src/offset.js @@ -5,7 +5,7 @@ var rtable = /^t(?:able|d|h)$/i, if ( "getBoundingClientRect" in document.documentElement ) { jQuery.fn.offset = function( options ) { - var elem = this[0]; + var elem = this[0], box; if ( options ) { return this.each(function( i ) { @@ -21,8 +21,14 @@ if ( "getBoundingClientRect" in document.documentElement ) { return jQuery.offset.bodyOffset( elem ); } - var box = elem.getBoundingClientRect(), - doc = elem.ownerDocument, + try { + box = elem.getBoundingClientRect(); + + } catch(e) { + box = { top: elem.offsetTop, left: elem.offsetLeft }; + } + + var doc = elem.ownerDocument, body = doc.body, docElem = doc.documentElement, win = getWindow(doc), diff --git a/test/unit/offset.js b/test/unit/offset.js index ed3d9622a..879753181 100644 --- a/test/unit/offset.js +++ b/test/unit/offset.js @@ -1,5 +1,14 @@ module("offset"); +test("disconnected node", function() { + expect(2); + + var result = jQuery( document.createElement("div") ).offset(); + + equals( result.top, 0, "Check top" ); + equals( result.left, 0, "Check left" ); +}); + var supportsScroll = false; testoffset("absolute"/* in iframe */, function($, iframe) {