ga-wdi-exercises / project1

[project] GA- Project 1
3 stars 75 forks source link

Click works but keydown does not #198

Closed dan-ator closed 9 years ago

dan-ator commented 9 years ago

I am trying to make it so clicking on a flash card will "flip it" (i.e. run the function that hides the front and shows the back). The "click" listener works but I can't get the keydown, keyup, or keypress to work here.

$("#frontOfCard").on(
  {click: flip},
  {keydown: flip}
);

$("#backOfCard").on(
  {click: flip},
  {keydown: flip}
);
dan-ator commented 9 years ago

I also tried different formatting for this, like .keydown, .keyup, etc.

RobertAKARobin commented 9 years ago

I think it's like this:

$("#frontOfCard").on({
  click: flip,
  keydown: flip
});
dan-ator commented 9 years ago

Still no dice.

RobertAKARobin commented 9 years ago

Then the problem may not be with the .on, but with something else. To find out, try splitting it into separate on statements:

$("#frontOfCard").on("click", flip);
$("#frontOfCard").on("keydown", flip);

$("#backOfCard").on("click", flip);
$("#backOfCard").on("keydown", flip);

This pretty much has to work. If it doesn't, the problem is elsewhere.

dan-ator commented 9 years ago

That one still didn't work for the keydown. But with assistance from a classmate, it seems like the issue was that it won't work while bound to frontOfCard or backOfCard. I instead switched it to body and it worked...but then even some keys seem to select my "next" button and in addition to flipping the card it also advances to the next.

RobertAKARobin commented 9 years ago

Ahh. Yeah, that would only work if #frontOfCard and #backOfCard are <input> fields.

If they're selecting the next button, maybe you need to preventDefault?

dan-ator commented 9 years ago

I am shaky on that. If I call a function like so:

$("body").on("keydown",flip);

then can I still insert an event and then a event.preventDefault?

dan-ator commented 9 years ago

Ok. I made it an anonymous function and then called flip inside of that after the event.preventDefault. It works, though any keyboard shortcuts are basically disabled.