Like the jQuery 1.7 on
method , overrides the live method. Although it does not have an easy way to pass or map selectors as you describe, it can be done by passing the dynamic value of data-events
instead of the type of event, if the value of the data-event corresponds to this event.
However, since the argument passed to the on on event parameter - the first parameter - is taken from each data-events attribute, from each element in the set of matched elements, we must scroll through the collection of matched elements so that we get separately the attribute value of the individual data-events of each element :
$('.js-test').each(function() { $(this).on( $(this).attr("data-events"), function() {
I want all events to be mapped to the same function, but different events trigger a function call for different DOM elements.
Since you want to match all events with one function, this solution meets your specific requirements and solves your problem.
However, if your requirements change and you find that you need to map a collection of function events to each type of event, this should start:
var eventFnArray = []; eventFnArray["click"] = function() { alert("click event fired - do xyz here"); // do xyz }; eventFnArray["mouseover"] = function() { alert("mouseover fired - do abc here"); // do abc }; $('.js-test').each( (function(fn) { return function() { $(this).on( $(this).attr("data-events"), function() { alert("hello - this is the " + $(this).attr("data-events") + " event"); // delegate to the correct event handler based on the event type fn[ $(this).attr("data-events") ](); }); } })(eventFnArray)); // pass function array into closure
UPDATE:
This has been tested and really works for new elements added to the div # container. The problem was how the on
method works. The delegating character on
only works if the parent element is included in the selector, and only if the selector is passed to the second parameter, which filters the target elements with the data-events attribute:
HTML:
<div id="container"> <a href="#" class="js-test" data-events="click">Test 1</a> <a href="#" class="js-test" data-events="mouseover">Test 2</a> </div>
JavaScript:
$(document).ready(function() { $('.js-test').each(function() { var _that = this; alert($(_that).attr("data-events")); $(this).parent().on( $(_that).attr("data-events"), '.js-test[data-events="'+ $(_that).attr("data-events") +'"]', function() {
Also, use the following jQuery to add an item to the container to validate it:
$('#container') .append("<a href='#' class='js-test' data-events='mouseover'>Test 3</a>");
Try:
Here is a jsfiddle that demonstrates tried and tested functionality.