2

Possible Duplicate:
Bind function to multiple events of different elements at once

I need to execute the same code for both a link click and change event

$(".foo").click(function() {

  //same code

}

$(".bar").change(function() {

  //same code

}

The normal way I would achieve is to create a function and then fire the function on each seperate event - but I'm wondering if jquery has an easier way to handle this, similar to

 $(".bar, .foo").

But obviously with different event methods.

To clarify i need one to click and one to change but NOT both to click and change, does that make sense?

Community
  • 1
  • 1
Jim SMith
  • 212
  • 3
  • 13
  • Defining a function (e.g. `foo`) and doing `$('.foo').click(foo); $('.bar').change(foo)` is the most DRY you can get with jQuery in this scenario (and there's nothing wrong with that). – Matt Jul 13 '12 at 12:55
  • @Matt that is equivalent to `$(".foo,.bar").on("click change", foo)`, isn't it? And that's what neal had from the start – Esailija Jul 13 '12 at 12:58
  • @Esailija: No, because the `foo` element doesn't have a `change` handler bound to it, and vice versa. – Matt Jul 13 '12 at 12:58

1 Answers1

10
$(".foo, .bar").on("click change", function(e){

    var myClass = $(this).is(".foo") ? "foo" : "bar";

    if(e.type === "change"){
         //DO STUFF UNIQUE TO CHANGE
    }
    else if(e.type === "click") {
         //DO STUFF UNIQUE TO CLICK
    }

    //DO STUFF THAT IS THE SAME

});
Naftali
  • 144,921
  • 39
  • 244
  • 303