-2

In my code,I have used 1000 ms as the duration value in animate function.Now I want to use a random value in place of this value.How can I do so?

<html>
<body>
<script src="jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function () {
$('#btn').click(function () {
$('#i1').animate({
'margin-left': '+=1155px'
},1000);
});
</script>
<img src="images.jpg" height="100px" width="200px" id="i1"><br>
<input type="button" value="start" id="btn">
</body>
</html>
user3298056
  • 7
  • 1
  • 6

2 Answers2

1

It should be simple as this as I think.

Use

Math.floor((Math.random()*100)+1);

Where *100 is the maximum value to be generated.

<script src="jquery-1.11.0.min.js"></script>
<script>
jQuery(function( $ ){ // Dom ready shorthand
  $('#btn').click(function () {
      $('#i1').animate({
        'margin-left': '+=1155px'
      }, Math.floor((Math.random()*1000)+1) );
  });
});
</script>

If you need to reuse your random on more places you can have some fun with your own reusable methods:

var MM = { // My Methods
   rand : function(min,max) { // RANDOMIZER
       return Math.floor(Math.random()*(max-min+1)+min);
   },  // comma separate 
   something : function() {
       // return your other method
   }
}

and use like MM.rand( minValue , maxValue);

$('#i1').animate({marginLeft: '+=1155'}, MM.rand(200, 1000) );
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
Waleed
  • 1,097
  • 18
  • 45
0

you can generate the random number in place as duration parameter of amimate() function then your code become

$(document).ready(function () {
$('#btn').click(function () {
$('#i1').animate({
'margin-left': '+=1155px'
},Math.floor((Math.random()*2000)+1000));
});

here generate the random number between 1000 and 2000.

Nilesh Nartam
  • 306
  • 2
  • 11