JQuery .on() method with multiple event handlers to one selector
Asked Answered
S

7

155

Trying to figure out how to use the Jquery .on() method with a specific selector that has multiple events associated with it. I was previously using the .live() method, but not quite sure how to accomplish the same feat with .on(). Please see my code below:

$("table.planning_grid td").live({
  mouseenter:function(){
     $(this).parent("tr").find("a.delete").show();
  },
  mouseleave:function(){
     $(this).parent("tr").find("a.delete").hide();        
  },
  click:function(){
    //do something else.
  }
});
       

I know I can assign the multiple events by calling:

 $("table.planning_grid td").on({
    mouseenter:function(){  //see above
    },
    mouseleave:function(){ //see above
    }
    click:function(){ //etc
    }
  });

But I believe the proper use of .on() would be like so:

   $("table.planning_grid").on('mouseenter','td',function(){});

Is there a way to accomplish this? Or what is the best practice here? I tried the code below, but no dice.

$("table.planning_grid").on('td',{
   mouseenter: function(){ /* event1 */ }, 
   mouseleave: function(){ /* event2 */ },
   click: function(){  /* event3 */ }
 });
Statecraft answered 22/12, 2011 at 18:14 Comment(0)
R
276

That's the other way around. You should write:

$("table.planning_grid").on({
    mouseenter: function() {
        // Handle mouseenter...
    },
    mouseleave: function() {
        // Handle mouseleave...
    },
    click: function() {
        // Handle click...
    }
}, "td");
Radiopaque answered 22/12, 2011 at 18:18 Comment(7)
Why isn't the selector $("table.planning_grid td") ?Invidious
@Muers, it would also work and the questioner acknowledges so, but also believes that he should bind the event on the <table> instead of each individual <td> element, which is indeed the right way to go.Hilliard
There is a good reason to use the .on on the <table> and not on the <td> and it's if you dynamically add <td>s later. $('table td').on... will only effect the <td> that are in the table the moment you call this function. $('table').on(... ,'td',function...) will effect any <td> you will add to this table later.Kalman
@Raanan, indeed, and in addition every event handler one registers has a cost, albeit tiny. When you're dealing with thousands of cells, registering a single handler on the <table> instead of one handler per <td> element becomes mandatory to achieve usable performance.Hilliard
@FrédéricHamidi This was a hard problem to Google; but I finally found your answer. Not even the jQuery docs was clear on this. Thank you!Kayekayla
Agreed. Very difficult to google this question as 'on' is such a common word and most results were related to .bind and .live. Good answer, just what I was looking for :D @Frédéric - Your link doesn't link to a header id on the jquery docs page anymore. Probably a result of updated documentation. But I could not find this answer on that page.Algie
Good job using the selector parameter. I am now using this approach for most Form event handlers and using the selector parameter to lazy attach.Electronegative
D
216

Also, if you had multiple event handlers attached to the same selector executing the same function, you could use

$('table.planning_grid').on('mouseenter mouseleave', function() {
    //JS Code
});
Dihydric answered 24/6, 2014 at 15:46 Comment(2)
this is what i was looking forGentianaceous
...and then get the actual fired event type with e.type (after adding the event as a parameter, i.e. ...function(e)...Gebler
A
33

If you want to use the same function on different events the following code block can be used

$('input').on('keyup blur focus', function () {
   //function block
})
Argentina answered 26/7, 2017 at 12:40 Comment(0)
K
15

I learned something really useful and fundamental from here.

chaining functions is very usefull in this case which works on most jQuery Functions including on function output too.

It works because output of most jQuery functions are the input objects sets so you can use them right away and make it shorter and smarter

function showPhotos() {
    $(this).find("span").slideToggle();
}

$(".photos")
    .on("mouseenter", "li", showPhotos)
    .on("mouseleave", "li", showPhotos);
Kahl answered 5/9, 2014 at 14:34 Comment(0)
C
9

And you can combine same events/functions in this way:

$("table.planning_grid").on({
    mouseenter: function() {
        // Handle mouseenter...
    },
    mouseleave: function() {
        // Handle mouseleave...
    },
    'click blur paste' : function() {
        // Handle click...
    }
}, "input");
Centralize answered 29/8, 2014 at 10:48 Comment(0)
A
1

Try with the following code:

$("textarea[id^='options_'],input[id^='options_']").on('keyup onmouseout keydown keypress blur change', 
  function() {

  }
);
Andris answered 26/10, 2016 at 13:24 Comment(0)
T
0

These days this should be:

$(document).on({
   mouseenter: function(e) {
     // Handle mouseenter...
   },
   mouseleave: function(e) {
     // Handle mouseleave...
   },
   'click blur paste' : function(e) {
     // Handle click...
   }
}, "<selector>");
Tillotson answered 6/10, 2023 at 12:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.