Jaspero
Jaspero

Reputation: 2972

How do I get the coordinates of a div?

I have used jQuery UI library to drag divs within a web page. While dragging, the div changes it's position and modifies CSS postion,top and left properties.

My questions are:

1) Is their a way in javascript to get the values of CSS properties and save on a variable(so that I can submit it to XML)? Those CSS properties are created on real time when dragging the divs.

2) Can I at least read the new coordinates of the div on the webpage?

My goal is to record those values so that when users logs in next time, their modified version of the web page is preserved.

Upvotes: 0

Views: 3297

Answers (2)

DMI
DMI

Reputation: 7191

To read the co-ordinates relative to the viewport, use offset():

var offset = $('#someitem').offset();
console.log('top: '+offset.top+'; left: '+offset.left);

To read the co-ordinates relative to the nearest positioned ancestor, use position():

var pos = $('#someitem').position();
console.log('top: '+pos.top+'; left: '+pos.left);

To get CSS properties, just use the css() function:

console.log($('someitem').css('top'));

Upvotes: 4

Marko
Marko

Reputation: 72222

you can easily get the offset of an element using jQuery.

var offset = $("#some-element").offset();

// Alert the values
alert("top: " + offset.top+ "left: " + offset.left);

Upvotes: 1

Related Questions