Jquery - Load div with random margins / position
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>
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.
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});
});
});
精彩评论