17

jQuery's 'live' method is unable to handle multiple events. Does anyone know of a good workaround to attach multiple events to a function that polls current and future elements? Or am I stuck using duplicate live methods for each event handler I need?

Example - I am trying to do something like:

$('.myclass').live('change keypress blur', function(){
  // do stuff
});
Will Peavy
  • 2,349
  • 3
  • 21
  • 21
  • are you trying to attach multiple handlers to the same event? or are you trying to attach a handler for many different events? – geowa4 Oct 29 '09 at 20:07
  • It sounds like he wants multiple events in the same handler, as if you could do $("a").live(["click","mouseover","doubleclick"], function() { //do stuff here}. Which you can't. – Jacob Mattison Oct 29 '09 at 20:15
  • I'm trying to do something like "$('.myclass').live("click keypress blur", function(){..." – Will Peavy Oct 30 '09 at 13:57

4 Answers4

19

As of jQuery 1.4.1 .live() can accept multiple, space-separated events, similar to the functionality provided in .bind(). For example, we can "live bind" the mouseover and mouseout events at the same time like so:

$('.hoverme').live('mouseover mouseout', function(event) {
  if (event.type == 'mouseover') {
    // do something on mouseover
  } else {
    // do something on mouseout
  }
});
Chris Fulstow
  • 41,170
  • 10
  • 86
  • 110
14

From jQuery 1.7, "on" function is what you're looking for :

$("a").on({
    click: function() {
        // do something on click
    },
    mouseenter: function() {
       // do something on mouseenter
    },
    mouseleave: function() {
         // do something on mouseleave
    }
});
TeChn4K
  • 2,317
  • 2
  • 21
  • 23
7

In jQuery 1.7 there is an API that allow you to do it easily...

$(".myClass").on({
    click: function(){
         alert("You click on me!");
    },
    mouseenter: function(){
         alert("Do you want click on me?");
    }
});

In my opinion this method is completely efficient and gathering all abilities that you can use in element's event....

Take a look at this page .on() [ jQuery 1.7 API ]

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
shahrokh nabavi
  • 102
  • 1
  • 4
1

Try in this way:

("#button").bind("click keyup", function(){

// your code goes here

}) 
Peter O.
  • 32,158
  • 14
  • 82
  • 96
surthi deepak
  • 81
  • 1
  • 2