views:

71

answers:

4

In jQuery is there a way of having something like:

if (button.click() || (keydown == 39)) {
   //stuff
}
+6  A: 

You can bind() to multiple events:

$(button).bind("click keydown", function (evt) {
    if (evt.type == "keydown" && evt.which == 39)
        alert("Key 39 pressed");
    else if (evt.type == "click")
        alert("Clicked!");
});

Example: http://jsfiddle.net/Bymug/

Note that the spacebar and enter keys may also fire the click event on a button.

Andy E
+1 - To elaborate, then just check for the presence of keyCode in the evt, test if == 39 then execute your 'stuff' or return.
mkoistinen
...and then check which one you got and handle the `keyCode == 39` bit.
T.J. Crowder
...and then that's it! +1
Reigel
@T.J.C, @mkoistinen: cheers, updated code sample.
Andy E
Won't this only respond to keydown events when the button is in focus? And, if it is, why bother?
mkoistinen
@mkoistinen: that question is better directed at the OP, he didn't specify that he wanted the keydown event on a separate element or object.
Andy E
True, but he didn't say he DIDN'T want that either. =)
mkoistinen
+6  A: 
function stuff(e) { alert('Something happened'); }

$('input[type=button]').click(function(e) { 
    stuff(e);
});

$(document).keydown(function(e) { 
    if (e.keyCode == 39) { stuff(e); }
});​​​

http://www.jsfiddle.net/4WuB5/

mkoistinen
Top stuff, will accept when SO lets me
Neurofluxation
This works fine for me, I have also voted up the above answer as well.
Neurofluxation
+2  A: 

You can use the live event and handle multple events:

$('.someClass').live('keydown mouseclick', function(event) {
  if (event.type == 'mouseclick') {
      // Do something
  } else if (event.type == 'keydown' {
      if (event.keyCode == '39')
      {
          // Do something
      }   
  }
});
GenericTypeTea
Why is live required here vs. bind?
mkoistinen
`.live()` works for existing and future matching elements. `.bind` only assigns to existing matches. They're one of the same really, but `.live` I find generally more useful. You can use either and get the same result.
GenericTypeTea
I understand the difference between live, bind (one and delegate), but I was curious why you stated that 'You need to use the `live` ...'. Sure it works, but I think it is sloppy to use `live` when `bind` (or `one` or `delegate`) is more appropriate.
mkoistinen
@mkoistinen - Sorry, my bad choice of wording. You don't *need* too, but I see your confusion so I updated the answer.
GenericTypeTea
+3  A: 

No, they are separate events, so you have to hook them up separately. You can use a named function to call from each event:

function x() {
  ...
}

$('.someclass')
  .click(x)
  .keydown(function(e){
    if (e.keyCode == 39) x(e);
  });
Guffa