views:

39

answers:

2

Hello. I'm looking to use jQuery to load Divs with random margins effecting the css. Below is the script I'm attempting use, trying to create a number random from 1-500, and loading that as the margin. But I'm not a jQuery wiz, and I'm missing something.

Thanks so much for the help!

<script type="text/javascript">

$(function(){

$("#randomnumber").load(function() {

            var numRand = Math.floor(Math.random()*501);


        $("#randomnumber").css("marginRight",numRand);


});

});

</script>



<div id="page-wrap">


        <div id="randomnumber">BIG BOY</div>

 </div>
A: 

your selectors always need to be in quotes.

$('#randomnumbers').css()

Also, it's up to you, but I would suggest following standard formatting conventions. It makes your code clearer for you and for others who would like to use it in the futures.

$(document).ready(function(){
    $("#randomnumber").load(function() {
         var numRand = Math.floor(Math.random()*501);
         $(this).css({'margin-right': numRand});
    });
});
Squirkle
ahh good call. thanks. though the margin seems to still not be effected?
Michael
Sorry. One correction I missed. Try it now.
Squirkle
squirkle, really appreciate the help. but it seems to still be having issues.you can see it here as the test: http://greyyy.com/random/index.html (note: i changed the margin to left, as i havent put down any other styles yet).
Michael
When I go to your demo site, the JQuery isn't loading. I think you missed some Google API code above the calls to load jquery.
ianhales
A: 

The problem is there is no .load() event for this element, at least not one that'll won't fire on load, you need a .each() like this:

$("#randomnumber").each(function() {
  var numRand = Math.floor(Math.random()*501);
  $(this).css({'margin-left': numRand});
});​

You can test that here, or since you're doing one element, make it simpler like this:

var numRand = Math.floor(Math.random()*501);
$("#randomnumber").css({'margin-left': numRand});​

You can test that version here.

Nick Craver
yes!!! that'll do it. thanks so much!
Michael