ekclone
ekclone

Reputation: 1092

Get the live position of a moving div?

I would like to know if there's a way to get the live position of a div using either .position() or .offset()?

Here's my js code

var div = $('.btn').position();

$( ".live-position" ).text( "left: " + div.left + ", top: " + div.top ); // Get position of $('.btn)

but this only works on reload, the coordinations are not changing when I move a div with jquery

Codepen

Upvotes: 0

Views: 1613

Answers (3)

Pugazh
Pugazh

Reputation: 9561

With setInterval you can acheive that. Read more here.

Below is an example. Updated CodePen

setInterval(function() {
  var div = $('.btn').position();
  $(".live-position").text("left: " + div.left + ", top: " + div.top);
}, 100);

$('.btn').animate({
  'margin-left': '200px',
  'margin-top': '70px'
}, 3000)
.btn {
  font-weight: bold;
  font-size: 5em;
}
.live-position {
  border: 1px solid black;
  margin: 1em;
  padding: 10px;
  display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="btn">
  text
</div>

<div class="live-position"></div>

Upvotes: 1

Daniel Z.
Daniel Z.

Reputation: 3348

It does work. The problem with your code is, that you set the position only on initialization. You could use setInterval to update your position every few milliseconds.

$('.btn').animate({ 'margin-left':'200px', 'margin-top':'70px'}, 3000)

setInterval(function(){
var div = $('.btn').offset();
$( ".live-position" ).text( "left: " + div.left + ", top: " + div.top );
}, 100);

https://jsfiddle.net/rpgpp2mp/

By the way, i changed position to offset, because i think thats what you want.

Upvotes: 2

webdevanuj
webdevanuj

Reputation: 675

try this:

setInterval(function() {
  var div = $('.btn').position();

   $( ".live-position" ).text( "left: " + div.left + ", top: " + div.top );
}, 1000);

check div position every 1 second

Upvotes: 1

Related Questions