Reputation: 83
I am trying to make an integer variable increment every time the Enter key is pressed. This variable is then used to output a value from an array.
$(document).keyup(function(e) {
if (e.keyCode == 13) {
console.log(++currSteps);
$('#output').text(outNum[currSteps])
if(outNum[currSteps] % 2 == 0){
$('body').css("background", "#4b84e5")
}
else if(outNum[currSteps] == 1){
$('body').css("background", "#9dd622")
}
else{
$('body').css("background", "#d16323")
}
}
});
The problem occurs when I actually press Enter. On the first press, it works properly, and increments the variable currSteps
and displays the next value in the array. However, when I press Enter again, it reverts it back to the original value of currStep
, as long as Enter is held down, it will display the original value.
Now, yes, this event is for keyup
, therefore it makes sense that things will work oddly on keydown
. However... if I open up the developer tools and click around in the console, and then return to my original window, the keyup
code works perfectly. Why is this only working after the developer tools have been opened?
I have tried this on jQuery 1.11.1 and 1.10.2.
Edit: currSteps
and outNum
declarations.
$('#in').click(function(){
$('#output').empty();
$('#steps').empty();
var steps = 0
currSteps = 0
var inNum = parseInt($('#input').val());
var col = '#ffffff'
outNum = []
outNum.push(inNum)
...
Upvotes: 1
Views: 262
Reputation: 10140
I allowed to myself to write a little of your missing variables defition: JSFiddle
$(document).ready(function() {
var currSteps = 0;
var outNum = { 0: 0, 1: 1, 2: 2 };
$(document).keyup(function(e) {
if (e.keyCode == 13) {
console.log(++currSteps);
$('#output').val(outNum[currSteps] + ' ' + currSteps)
if(outNum[currSteps] % 2 == 0){
$('body').css("background", "#4b84e5")
}
else if(outNum[currSteps] == 1){
$('body').css("background", "#9dd622")
}
else{
$('body').css("background", "#d16323")
}
}
});
});
Is you problem still actual with upper demo?
Upvotes: 1