Wednesday, 25 September 2013

jQuery offset() not working properly in Internet Explorer

Strictly speaking, maybe it works in Internet Explorer and not Chrome but the effect looks wrong in IE 10 so I'll assume that's the case.

Scenario? I have some transparent windows that are used to frame images so that the user can click on the transparent window and see the image full-screen. In order to do this, I iterate the images, create a new frame for each one and set its position using offset() to match that of the parent image. position: absolute and everything is fine in Chrome.

Same page in IE and the frames are not positioned above the images but are below them, causing the parent div to stretch and basically it's all rubbish. A quick check and in IE, these frames have position: relative which they don't in Chrome (since my CSS specifies absolute).

A dig through the jQuery source and the offending (and slightly odd) line of code is:

// set position first, in-case top/left are set even on static elem
        if ( position === "static" ) {
   = "relative";

Which is presumably true in IE by default but not in Chrome (despite my CSS specifying absolute!). Anyway, I found a bug filed on jQuery here which describes it in more technical detail. The bug seems undecided even though it is clearly inconsistent behaviour but more importantly, Kelly Selden has proposed a workaround (which does work!) using css() instead of offset:

targetElement.css('left', source.offset().left).css('top', source.offset().top);

Thanks Kelly!
Post a Comment