Finding the position or coordinates of a div element in Blazor

I am currently working on a popup component that needs to be movable. The default position is set to top:0;left:0;, causing the popup to appear in the top-left corner of the page. However, I want it to be centered on the page and then retrieve the Top Left coordinates of the div for further calculations.

This is the current setup:

<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() {
        //Code to set offsetX & offsetY to the top left div position goes here
    }

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

    private void OnDragEnd(DragEventArgs args) {
        offsetX += args.ClientX - startX;
        offsetY += args.ClientY - startY;
    }
}

Answer №1

Currently, the functionality is only available through JavaScript

public class ElementPosition
{
    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<ElementPosition>("GetElementPosition", MyElementReference);

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

and

<script> GetElementPosition = (element) => { return element.getBoundingClientRect(); }; </script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjusting website design size when zooming and switching resolutions

<html> <style> body { background-color:#F1EEF2; } header { width:800px; margin-left:auto; margin-right:auto; } layout { min-width: 100%; min-height: 100%; } nav.header { width:800px; height:40px; background-color:#000000; color:#fef8f0; } ...

What causes the discrepancy in margin values between desktop and mobile devices?

In my project, I have a collection of div elements that need to be spaced vertically from one another by the height of the window plus an additional 100px. However, I encountered a discrepancy when setting this margin using jQuery between mobile and deskto ...

Looking to develop a swipeable card feature similar to Gmail using React JS (excluding React Native)?

Looking to replicate the swipe card functionality of Gmail in React Js, After creating the UI and implementing swiping using UseGeature, I am facing an issue with smooth animation when hiding or showing buttons using UseEffect. There is a 20px movement be ...

The randomness of a generated string is compromised if it is called multiple times

I'm having trouble generating a random string of words in a WebForms page using C# and ASP.NET. It works fine when called once, but when I call it multiple times in a row during a PostBack, it repeats the same random string each time. I suspect there ...

Animation not fluid with ReactCSSTransitionGroup

Currently, I am in the process of developing an image carousel that showcases images moving smoothly from right to left. However, despite its functionality, there seems to be a slight jaggedness in the animation that I can't seem to resolve. Interesti ...

Determining the orientation of an image in JavaScript

Currently, I am attempting to determine the orientation of images using JavaScript in order to apply a specific class to them. This process seems to be functioning correctly on Firefox, but is presenting challenges on other browsers. It appears to work bet ...

Is there a way to seamlessly transition the visibility of the Bootstrap 5.3 Spinner as it loads and unloads?

After delving into some research regarding Bootstrap-compatible spinners, I stumbled upon a piece of code. Take a look: function getData() { var spinner = document.getElementById("spinner"); spinner.style.display ...

The chosen value is deemed invalid as it is not found within the available list of items

Here is the error message I am receiving: 'ddlRankEdit' has a SelectedValue that is considered invalid because it does not exist in the list of items. Parameter name: value I have a form with multiple dropdown lists nested within a panel tha ...

How can a new <li> element be created without being influenced by certain CSS styles?

I am attempting to enhance my menubar by adding a signup/login item aligned on the right without affecting the other center-aligned items. Essentially, I have an entry named "Login/Sign Up" that should maintain its own unique style while seamlessly blendin ...

Basic Jquery CSS style requests

Can you help me troubleshoot this issue? var hover = $('<img />').attr('src', hovers[i]).css('position', 'absolute') I'm having trouble getting th ...

Differences between FindAll and Predicate<TSource> versus Func<TSource, bool>

I'm having trouble understanding why the method List<T>FindAll(...) doesn't accept Func<TSource, bool>, but instead requires Predicate<TSource>. For example, when I have a List of books and I only want to retrieve books that ar ...

What could be preventing my bootstrap class from being applied as expected?

As a newcomer to HTML, CSS, and bootstrap, I am struggling with updating my stylesheet values in the preview. This is the button tag that I am working with: <button class="btn btn-primary btn-xl">Find out More</button> However, when ...

Issues with "System.MissingMethodException: 'No parameterless constructor specified for type XXX'" in .Net Core 3.1

Hello, I am looking for help with properly implementing the following code: This is my Controller: [Route("api/[controller]")] [ApiController] public class TerminalsController : ControllerBase { private readonly IServiceWrap ...

Is the Bootstrap navigation bar collapse button visible on larger screens?

How can I make my Bootstrap navbar collapse button work on big screens the same way it does on mobile devices? <nav class="navbar navbar-expand-md navbar-light bg-light"> <a class="navbar-brand" href="#">Default</a> <button ...

URL displays the bootstrap carousel slider item's ID

The URL displays the ID of each slide on the bootstrap carousel slider, as shown in the images below: https://i.sstatic.net/TWcx2.png https://i.sstatic.net/xaJxm.png When changing sliders, the URL reflects the ID of each slide. After upgrading to a newe ...

"PushSharp's notification queue seems to be experiencing a standstill - no progress is being

I attempted to utilize PushSharp library to send Apple push notifications in the following manner: public class Push { private readonly PushBroker _push; private static Push _instance; public static Push Instance { get { return _ ...

Unable to execute a basic opacity transition on a div element

Why isn't the opacity transitioning in Chrome? I only want it to fade in with the 'transitions' class without fading out first. Check out this code sample: http://jsfiddle.net/chovy/t37k3/9/ <div></div> <a href="#" class="s ...

The images in my gallery refuse to hover or respond to my clicks

Ever since integrating this cropping effect (http://jsfiddle.net/BPEhD/2/) to my gallery images, I've encountered an issue - the hover state is missing and I can't click on the images either. Although the pointer cursor appears when I hover over ...

How to align text to the left and right within a Bootstrap accordion

I am currently working on a Bootstrap accordion, and I have a specific layout in mind. I want to display text on both the left and right sides of the accordion header, right next to the arrow that expands and collapses the content: https://i.sstatic.net/d ...

Seeking guidance on implementing toggle buttons for navigation bar items on mobile screens, enabling them to toggle for a dropdown menu. The tools at my disposal are HTML, CSS

I want to make the navigation menu responsive by adding a toggle button for the dropdown menu on mobile screens. Here is the code snippet: .nav-link { display: inline-block; position: relative; color: black; } html,body{ height: 100%; width ...