Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 491
  • Last Modified:

HTML element position

Hi,

I'm using 'elementFromPoint' to return me an html 'element' object. this works fine. I would like to know the element's left and top coordinates.
Any ideas?
0
fidel83
Asked:
fidel83
  • 3
  • 2
1 Solution
 
MrJulCommented:
I wrote this little function which do the trick :
You have to use offsetLeft & offsetTop, but since those properties returns parent-relative coordinates, the function loops through all parents.
At the end, you have absolute coordinates.

function GetElemCoordsFromPoint(WB: TWebBrowser; X, Y: Integer): TPoint;
var
    Doc: IHTMLDocument2;
    Elem: IHTMLElement;
begin
    Result.X := 0;
    Result.Y := 0;
    Doc := WB.Document as IHTMLDocument2;
    Elem := Doc.elementFromPoint(X, Y);
    while Elem <> nil do
    begin
        Inc(Result.X, Elem.offsetLeft);
        Inc(Result.Y, Elem.offsetTop);
        Elem := Elem.offsetParent;
    end;
end;
0
 
MrJulCommented:
PS: you have to put MSHTML in your uses clause.
0
 
fidel83Author Commented:
hey MrJul,
I'm using 'variant' for the internet explorer object. is there a way to convert your code so that it works with this?
0
 
MrJulCommented:
It depends of what is stored in your Variant.
If it is a IWebBrowser2 interface as I suspect, do the following :

Replace
function GetElemCoordsFromPoint(WB: TWebBrowser; X, Y: Integer): TPoint;

By
function GetElemCoordsFromPoint(WB: IWebBrowser2; X, Y: Integer): TPoint;

Then use the following code to call the function :
(V is assumed to be your Variant)

var
    Pt: TPoint;
    VarData: PVarData;
begin
    VarData := FindVarData(V);
    GetElemCoordsFromPoint(IWebBrowser2(VarData^.VDispatch), X, Y);
0
 
fidel83Author Commented:
thanks MrJul,
I ended up changing my code to use IHTMLDocument2
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now