JQuery - convert .live () to .on ()

How do I combine this old jQuery code in v1.7 .on() ?

v1.3 .live() :

  $('#results tbody tr').live({ mouseenter: function () { $(this).find('.popup').show(); }, mouseleave: function () { $(this).find('.popup').hide(); } }); 

v1.7 .on() :

 $('#results tbody').on('mouseenter', 'tr', function () { $(this).find('.popup').show(); }); $('#results tbody').on('mouseleave', 'tr', function () { $(this).find('.popup').hide(); }); 

I want to pass both event handlers to a single .on() call, but saving the wonderful .on() event allows me to do so.

Thanks!

+6
source share
4 answers

You can pass an event map as the first parameter:

 $('#results tbody').on({ 'mouseenter' : function () { $(this).find('.popup').show(); }, 'mouseleave' : function () { $(this).find('.popup').hide(); } }, 'tr'); 

JQuery documentation :

.on (events-map [, selector] [, data]) ,
events-map A map in which string keys represent one or more types of events, separated by spaces, and optional namespaces, and values ​​represent a handler function that must be called for the event (s).

+10
source

I just want to pass both event handlers to a single object, as in the first example.

In this case, you can attach two events together, and then distinguish them in the handler itself, for example:

 $('#results tbody').on('mouseenter mouseleave', 'tr', function (e) { if (e.type == "mouseenter") { $(this).find('.popup').show(); } else { $(this).find('.popup').hide(); } }); 
+3
source

The formats used are indicated in the documentation for live

 $(document).on({...events...}, selector, data); 

-or -

 $(document).on(event, selector, data, callback); 

The code for the live function in 1.7+ is now just an end-to-end function:

 live: function( types, data, fn ) { jQuery( this.context ).on( types, this.selector, data, fn ); return this; } 
+1
source

The first example and changing live to on should be all you need

  $('#results tbody tr').on({ mouseenter: function () { $(this).find('.popup').show(); }, mouseleave: function () { $(this).find('.popup').hide(); } }) 

See: http://api.jquery.com/on/#example-6

0
source

Source: https://habr.com/ru/post/915990/


All Articles