Doug Smith
Doug Smith

Reputation: 580

using a variable to define position in javascript/jquery

I'm testing out some code for making names float around randomly. My general question is how do we apply variables to style attributes? My specific example is as follows. First I tried this:

<body>
Is this it?
<button id="go">&raquo; Run</button>
<div id="floatName" style="left:50px; top:150px">James</div>
<div id="n2">Sarah</div>

<script>$( "#go" ).click(function() {
  $( "#floatName" ).animate({
    left: "100px",
    top: "200px"
  }, 500, function() {
    // Animation complete.
  });
  $( "#2" ).animate({
    left: "300px",
    top: "20px"
  }, 500, function() {
    // Animation complete.
  });
});
</script>

</body>

This works as I expected. Next I wanted to randomize the animation to that the left and top change. However, I don't know how to do this. One try looks like this:

  $( "#floatName" ).animate({
    x = Math.random()*500
    y = Math.random()*500
    left: x + "px",
    top: y + "px"
  }, 500, function() {
    // Animation complete.
  });

Obviously didn't work and I'm having problems finding the solution.

Upvotes: 0

Views: 84

Answers (1)

Majid Laissi
Majid Laissi

Reputation: 19788

http://jsfiddle.net/veqne72f/

 $( "#floatName" ).animate({
   left: Math.random()*500 + "px",
    top: Math.random()*500 + "px"
  }, 500, function() {
   // Animation complete.
 });

Upvotes: 1

Related Questions