Click here to Skip to main content
15,880,608 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
I want to create a slider div which move random position on the html documents with Jquery (animate function).
My HTML code is :-

HTML
<html>
<head>
<script src="scripts/jquery-1.8.3.min.js">
</script>
<script> 
$(document).ready(function(){
  $("#bu1").click(function(){
var temp=parseInt(Math.random()* document.body.clientWidth);
temp="'"+temp+"px'";
    $("div").animate({left:temp});
  });
});
</script> 
</head>
 
<body>
<button id="bu1">Start Animation</button>
<div style="background:#98bf21;height:100px;width:100px;position:absolute;">
</div>

</body>
</html>


when I run this its doesn't move that div ...
how to write that Math.Random value in CSS ????

thanks in advanced..
Posted

Instead of complicating it by adding the "px" (and inadvisably mixing datatypes), just leave it as a bare number. The JQuery docs state that
Quote:
Property values are treated as a number of pixels unless otherwise specified.

So just remove this line:
temp="'"+temp+"px'";
 
Share this answer
 
Comments
JayantaChatterjee 18-Apr-13 8:54am    
Thank You Sir....
Change this
JavaScript
temp="'"+temp+"px'";

with this
JavaScript
temp = temp+"px"


this
JavaScript
temp="'"+temp+"px'";

it's like you are writing
CSS
div{
  left: '100px';
}

wich is not valid
 
Share this answer
 
v2
Comments
Moykn 18-Apr-13 8:10am    
Don't understand why my answer was downvoted, despite jQuery treating number as pixels otherwise specified if he needs to use "%" or "em" this
temp="'"+temp+"%'";
or this
temp="'"+temp+"em'";
will still be wrong. Removing the line temp="'"+temp+"px'"; will make the code works but it's not showing what is wrong.
Brian A Stephens 18-Apr-13 8:47am    
You are right, sorry. I changed my vote. Your answer is valid and applies to some alternate situations too. When I first read your answer, I misunderstood what you were saying.
Moykn 18-Apr-13 8:54am    
Thank you. But you are right too, i know jQuery treats numbers as "px" and i should have considered this in my answer, to make it more precise.
JayantaChatterjee 18-Apr-13 8:54am    
Thanks a Lotttttttttttt its works....
thanks again Sir....

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900