Two events at a time

I want to do some action when clicking .smth class

$('.smth').click(function() {

and when you press a key:

$('.txt').bind('keypress', function(e) {

I want to do the same action, so how can I use them with both OR and similar?

$('.log').click.or.$('.txt').bind('keypress', function(e) {

?

Refuse.

+5
source share
3 answers

If it was the same set of elements you could use:

$(".myclass").bind("click keypress", function(event) {
    //...
});

But since these are different elements, you will need to follow the advice of Felix and write a function, and then attach it as an event handler.

+13
source

Use a named function instead of an anonymous one.

function handler() {
    //...
}

$('.txt').keypress(handler);
$('.smth').click(handler);
+7
source

,

$(".smth, .txt, .log").bind("click keypress", function(event) {
    console.log("key pressed");
});
0

All Articles