Reputation: 113
For some reason when I call this function it only works on the first keydown. Im not sure what I'm doing wrong.
$(document).ready(function(){
$(document).keydown(function(e) {
var x = 10;
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 40){
function rise(x){
$('#div2').css('bottom',x+'%');
}
rise(x);
x++;
}
Upvotes: 0
Views: 92
Reputation: 382092
You don't see it working because you reinitialize x
to 10
every time.
A solution is to put x in the external scope :
$(document).ready(function(){
var x = 10;
$(document).keydown(function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
function rise(x){
$('#div2').css('bottom',x+'%');
}
rise(x);
x++;
});
});
Note that there's no reason to define a rise
function here. You could simply do
$(document).ready(function(){
var x = 10;
$(document).keydown(function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
$('#div2').css('bottom',x+'%');
x++;
});
});
(I hope there's a reason for the code
part).
Upvotes: 3