Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor get div position / coordinates

I'm creating a popup component and I want this to be movable. I can move it using the top / left style, but for now they are init to top:0;left:0; and so the popup appear on the top left corner of the page. I'm looking to make it appear on the center of the page and then get the Top Left coordinates of my div in ordor to manage properly my calcul after.

here is what I have now:

<div class="child-window" draggable="true" style="position:absolute; top: @(offsetY)px; left: @(offsetX)px; border-color: black;" @ondragend="OnDragEnd" @ondragstart="OnDragStart">
   <div class="cw-content">
      @Content
   </div>
</div>

@code {
   private double startX, startY, offsetX, offsetY;

   protected override void OnInitialized() {
        base.OnInitialized();
        ResetStartPosition();
    }

   private void ResetStartPosition() {
        //Set offsetX & offsetY to the top left div position
    }

   private void OnDragStart(DragEventArgs args) {
        startX = args.ClientX;
        startY = args.ClientY;
    }

    private void OnDragEnd(DragEventArgs args) {
        offsetX += args.ClientX - startX;
        offsetY += args.ClientY - startY;
    }
}
like image 852
yToxide Avatar asked Jan 07 '20 16:01

yToxide


1 Answers

At the moment it is possible with JS only

public class BoundingClientRect
{
    public double X { get; set; }
    public double Y { get; set; }
    public double Width { get; set; }
    public double Height { get; set; }
    public double Top { get; set; }
    public double Right { get; set; }
    public double Bottom { get; set; }
    public double Left { get; set; }
}

private async Task OnElementClick(MouseEventArgs e)
{
    var result = await JSRuntime.InvokeAsync<BoundingClientRect>("MyDOMGetBoundingClientRect", MyElementReference);

    var x = (int) (e.ClientX - result.Left);
    var y = (int) (e.ClientY - result.Top);
   
   // now you can work with the position relative to the element.
}

and

<script> MyDOMGetBoundingClientRect = (element, parm) => { return element.getBoundingClientRect(); }; </script>
like image 121
henon Avatar answered Sep 17 '22 15:09

henon