somewhereinsf
somewhereinsf

Reputation: 21

Different actions on multiple Keydown event

Okay, so my question (im hoping) is fairly simple. I want to know what to do so that I can create different events for the same keycode. For instance Id like to fade out a div and fade a new one in on the first keypress, then fade that one out and fade a new one in on keypress.

Thanks!

$(document).keydown(function() {
  if (event.keyCode == '40') {

    $('.div-1').fadeOut("slow")
    $('.div-2').fadeIn("slow")

   // I'd like this event to occur on the Second keydown

    $('.div-2').fadeOut("slow")
    $('.div-3').fadeIn("slow")
   }  
});

Upvotes: 1

Views: 769

Answers (2)

griZZZly8
griZZZly8

Reputation: 694

The only solution I can see is create local variable. In your case (slodeshow) you need to count each keydown and parse div class.

    var hits = 0;

    $(document).keydown(function() {
      if (event.keyCode == '40') {          
          $('.div-' + hits).fadeOut("slow")
          $('.div-' + (hits + 1)).fadeIn("slow")         
          hits++;
       }  
    });

Upvotes: 0

Reigel Gallarde
Reigel Gallarde

Reputation: 65264

try

var hits = 0;

$(document).keydown(function() {
  if (event.keyCode == '40') {
    hits++;
    if (hits % 2 == 0) {
       // I'd like this event to occur on the Second keydown
       $('.div-2').fadeOut("slow");
       $('.div-3').fadeIn("slow");

    } else {

      $('.div-1').fadeOut("slow");
      $('.div-2').fadeIn("slow");
   }  
});

Upvotes: 1

Related Questions