Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax for using selector in .on() method event-map?

I'm trying to create an .on() method using events-map. I want to change this: $("ul").on("click", "li", function() {...}); to something like this:

$("ul").on({
    click: function() {...},
    mouseenter: function() {...},
    mouseleave: function() {...}
});

Where do I put the selector "li" in the events-map?

like image 857
mtl Avatar asked Dec 06 '22 16:12

mtl


2 Answers

You just put it as the second argument as usual:

$("ul").on (
  {
    click: function() { ... },
    mouseenter: function() { ... },
    mouseleave: function() { ... }
  },
  'li'
);

From the docs:

.on( events-map [, selector] [, data] )

events-map A map in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s).

selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element.

data Data to be passed to the handler in event.data when an event occurs.

Parameters enclosed in [] are optional. So, if you do not pass a selector, the events are bound to the elements in the jQuery object, in this case all ul-elements on the page. If, however, the selector is provided, then the elements in the jQuery objects handles event delegation for the set of elements matched by the selector. I.e when an event occurs on an element matching the selector that is a descendant of the element in the jQuery object, that event handler will be called once the event has bubbled its way up to the parent. Note that this means that if the event propagation is canceled before it reaches the parent, the event handler will not be called.

like image 172
PatrikAkerstrand Avatar answered Dec 10 '22 13:12

PatrikAkerstrand


After the events-map:

$("ul").on ({
    click: function() { ... },
    mouseenter: function() { ... },
    mouseleave: function() { ... }
}, "li");

Example: http://jsfiddle.net/pPPW4/

Per the docs:

.on( events-map [, selector] [, data] )

like image 22
Andrew Whitaker Avatar answered Dec 10 '22 12:12

Andrew Whitaker