Reputation: 13
My following code will not function, unless I place it all
$(window).load(function(){
// within here
}
How can I get my code to run without requiring the above function? Thanks!
My code:
// Player controls
var timer = null;
$('#left').mousedown(function() {
moveLeft(); // Do it now
timer = setInterval(moveLeft, 5); // Then every 100 ms
}).mouseup(function() {
clearInterval(timer); // And stop it
});
function moveLeft() {
var nextpos = parseInt($('#player').css('left')) - 5;
if (nextpos > 0) {
$('#player').css('left', nextpos + 'px');
}
}
$('#right').mousedown(function() {
moveRight(); // Do it now
timer = setInterval(moveRight, 5); // Then every 100 ms
}).mouseup(function() {
clearInterval(timer); // And stop it
});
function moveRight() {
var nextpos = parseInt($('#player').css('left')) + 5;
if (nextpos < PLAYGROUND_WIDTH - 100) {
$("#player").css("left", ""+nextpos+"px");
}
}
// Timer
$(function(){
var timercount = 30;
countdown = setInterval(function(){
$("#timer").html(timercount);
if (timercount <= 0) {
$("#timer").html("TIMES UP");
}
timercount--;
}, 1000);
});
Upvotes: 0
Views: 101
Reputation: 7954
You have to put it below your HTML..
<body>
//your html stuff here that uses the script
<script type="text/javascript">
// the js code here
</script>
</body>
Upvotes: 0
Reputation: 4868
If you run the code at the end of the page, rather than in the header, those elements should be loaded by the time the javascript runs.
That said, if your code is comparing the size of images, the images need to be loaded first...
Upvotes: 0
Reputation: 5460
I'm going to assume you're not trying to get a comparison of why you need $(window).load and not $.ready. Anyway, javascript is run as it's seen. You've got jquery looking up elements (#right, #player, etc) that probably haven't been loaded into the page yet. So, because these elements are not on the page, jQuery can't bind these events to them.
Read this through - it may more thoroughly answer your question. http://api.jquery.com/ready/
Upvotes: 2