user686605
user686605

Reputation:

Coordinates of HTML elements

I am going to create a selection 'lasso' that the user can use to select portions of a table. I figured that positioning a div over the region is far easier than trying to manipulate the cell borders.

If you don't understand what I mean, open up a spread sheet and drag over a region. I want the div to align perfectly with the cell borders.

I have a very good idea of how to do this, but how would I get the (x,y) coordinates (screen position) of a table cell (td)?

Upvotes: 6

Views: 8409

Answers (4)

rnofenko
rnofenko

Reputation: 9533

For those who doesn't want to use jquery:

var coordinates = td.getBoundingClientRect();
console.log(coordinates.left, coordinates.top, coordinates.right, coordinates.bottom);

Upvotes: 0

gilly3
gilly3

Reputation: 91567

Use .offset() along with .height() and .width() if necessary.

var td = $(someTDReference);
var pos = td.offset();
pos.bottom = pos.top + td.height();
pos.right = pos.left + td.width();
// pos now contains top, left, bottom, and right in pixels

Edit: Not .position(), use .offset(). Updated above.

Edit: Changed pos.width() to td.width()

Upvotes: 7

jackrugile
jackrugile

Reputation: 1663

Hey you should be able to do it like this (jsFiddle): http://jsfiddle.net/jackrugile/YKHkX/

$('td').hover(function(){
    var xPos = Math.floor($(this).offset().left);
    var yPos = Math.floor($(this).offset().top);
});

The Math.floor gets rid of the crazy decimals and makes it easier to work with in my opinion. Hope that helps!

Upvotes: 3

Khurram Ijaz
Khurram Ijaz

Reputation: 1864

you can use pageX and pageY to trackdown the mouse cursor x , y

$("#your_div").mouseover(function(e))
{
    x = e.pageX;
    y = e.pageY;
}

you can set the div border to highlight the div on mouseover simply by

$("#your_div").css("border","1px solid black");

this will kinda show current div selectable effect...

that if if the div is

position:fixed and then you can read its left and top property

hope that helps you

Upvotes: 2

Related Questions