seus seus - 6 months ago 8
jQuery Question

updating a variable jquery on event change

I am creating a interactive experience using jQuery. I am trying to make it so my character can go into multiple rooms.

$(document).keydown(function(e) {
switch (e.which) {
case 39:
$("#barry").attr("src", "img/characters/BarryBallRight.png")
$("#barry").stop().animate({
left: 1021
}, 1250, function() {
position = $(this).position();
getCurrentPos(position);
if (barryPosX > $("#canvas").width()) {
if (state == 0) {
state = 1
changeBackground(state);
// reset barry
$(this).css({
'left': '-100px'
});
$(this).stop().animate({
left: '+=150px'
})

};
if (state == 1) {
state = 2;
changeBackground(state);
// reset barry
$(this).css({
'left': '-100px'
});
$(this).stop().animate({
left: '+=150px'
})
};
};
})


My problem as you can see is that the last state that runs overwrites the previous one, meaning that the
changeBacktround()
function will change the background of the most recent
state
that is set i.e
2


I know there is some logic I am missing.

Note that the
getCurrentPos()
function just retrieves the current
$("#barry")
position on screen. The
changeBackground()
function is switch statement that takes the current state and changes the screen background accordingly.

Thanks in advance.

Kbi Kbi
Answer
if (state == 0) {
   state = 1
   changeBackground(state);
   // reset barry
   $(this).css({
   'left': '-100px'
   });
  $(this).stop().animate({
  left: '+=150px'
    })

   } else if (state == 1) {
      state = 2;
      changeBackground(state);
      // reset barry
      $(this).css({
       'left': '-100px'
      });
      $(this).stop().animate({
       left: '+=150px'
        })
      };

As far as i understand you need to use else if. Right now hes always going into the 2nd if if the state starts with 0. With else if its going either into state == 0 or into state == 1 but not into both