Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't access the visual location of an element with JS

I have a multi-column layout in a UIWebview (webkit control) but I'm having problems accessing the 'visual' location of an element.

I shift tapX by 4096 (4 x 1024, where 1024 is the height of a 'columnated page'), and get the correct 'tapped' element, but I cannot tell whether I'm at the edge or in the middle of the element. I need the absolute top and left positions, so I can animate a layer effect over the top of the element using a rect of (e.left, e.top, width, height) - obtaining the correct e.left and e.top is proving tricky.

tapElement.offsetTop ignores the column layout and the transform does not appear to work.

var tapElement  = document.elementFromPoint(tapX, tapY);

if (!tapElement)
    return;   

var realLeft    = window.getComputedStyle(tapElement).getPropertyValue("offsetLeft");
var realTop     = window.getComputedStyle(tapElement).getPropertyValue("offsetTop");

Solution:

// Figuring out the real top and left positions is difficult
// under the CSS3 multi column layout... But this works :) 

/*
// jQuery method
var realLeft    = $(tapElement).offset().left;
var realTop     = $(tapElement).offset().top;
*/

// DOM method
var box = tapElement.getBoundingClientRect();
var doc = tapElement.ownerDocument;
var docElem = doc.documentElement;
var body = doc.body;
var win = window;
var clientTop = docElem.clientTop || body.clientTop || 0;
var clientLeft = docElem.clientLeft || body.clientLeft || 0;
var scrollTop = win.pageYOffset || docElem.scrollTop || body.scrollTop;
var scrollLeft = win.pageXOffset || docElem.scrollLeft || body.scrollLeft;
var realTop = box.top + scrollTop - clientTop;
var realLeft = box.left + scrollLeft - clientLeft;   
like image 532
Matt Melton Avatar asked Nov 07 '11 17:11

Matt Melton


1 Answers

You could try the JQuery method "offset". Here is the documentation for it. http://api.jquery.com/offset/

If you can't use JQuery directly, examining the code may help solve your problem. (Grab the debug version for that.)

like image 132
John Fisher Avatar answered Nov 11 '22 22:11

John Fisher