Click here to Skip to main content
12,405,700 members (64,367 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: Javascript HTML jQuery
I want to create a slider div which move random position on the html documents with Jquery (animate function).
My HTML code is :-

<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 17-Apr-13 5:16am
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

Change this
temp="'"+temp+"px'";
with this
temp = temp+"px"

this
temp="'"+temp+"px'";
it's like you are writing
div{
  left: '100px';
}
wich is not valid
  Permalink  
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.
Jayanta Chatterjee 18-Apr-13 8:54am
   
Thanks a Lotttttttttttt its works....
thanks again Sir....
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

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'";
  Permalink  
Comments
Jayanta Chatterjee 18-Apr-13 8:54am
   
Thank You Sir....

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web02 | 2.8.160721.1 | Last Updated 17 Apr 2013
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100