Friday, June 1, 2012

Obtain Element Coordinates Using JQuery

I'm working on a project with ASP.NET and JQuery where I need to be able to obtain the coordinates for a div element in response to a button click. I found an example here, but I wanted to get not just the top and left values, but be able to obtain coordinates of all four corners.

To do this, I make use of JQuery's position, height, and width functions, then simply use some arithmetic to obtain the coordinates and finally display them. 

Here's an example. First, the markup:
<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

Div Coordinates





I am a div.

Now, the code behind: 

protected void Button1_Click(object sender, EventArgs e)
{
     Label1.Text = "Top Left: " + hfTop.Value + ", " + hfLeft.Value;
     Label2.Text = "Top Right: " + hfTop.Value + ", " + hfRight.Value;
     Label3.Text = "Bottom Left: " + hfBottom.Value + ", " + hfLeft.Value;
     Label4.Text = "Bottom Right: " + hfBottom.Value + ", " + hfRight.Value;
}



In a nutshell, the button click first triggers the OnClientClick event, which calls the JQuery functions to populate the values of the HiddenField objects. Then, the OnClick method takes those values and concatenates them in the code behind into coordinate pairs to display as the label text.
In cases where we need specific coordinates of each corner of a div element in response to a click event, this method works nicely.



No comments: