Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to use jQuery's on(..) to dynamically bind to multiple events
    primarykey
    data
    text
    <p>I am trying to create leverage jQuery's .on() (ex-live()) to bind multiple events. It is working for elements which exist on document.ready, but if i dynamically add a second link after page load, my event handler isn't triggered.</p> <p>This makes sense since the outer-most method iterates over the elements, and doenst listen for newly added DOM nodes, etc. The .on(..) is what listens for new DOM nodes, but requires an event name params, which I dont have until I have the DOM node.</p> <p>Seems like a chick and the egg sort of situation.</p> <p>Thoughts?</p> <pre><code>&lt;a href="/foo.html" class="js-test" data-test-events="['click', 'mouseover']"&gt;Test 1&lt;/a&gt; &lt;a href="/foo.html" class="js-test" data-test-events="['mouseout']"&gt;Test 2&lt;/a&gt; $(function() { $('.js-test').each(function() { var $this = $(this); var e, events = $this.data('test-events'); for(e in events) { $this.on(events[e], function() { console.log("hello world!") }); } }); }); </code></pre> <p>Update, The following does seem work either; $(this) doesnt appear to be in the right scope.</p> <pre><code>&lt;a href="/foo.html" class="js-test" data-test-events="click mouseover"&gt;Test 1&lt;/a&gt; &lt;a href="/foo.html" class="js-test" data-test-events="mouseout"&gt;Test 2&lt;/a&gt; $(function() { $('.js-test').on($(this).data('test-events'), function() { // call third party analytics with data pulled of 'this' }); }); </code></pre> <hr> <p>Update 1:</p> <p>I think my best bet will be to create special .on methods for all the methods I want to support like so:</p> <pre><code>$(document).on('click', '.js-test[data-test-events~="click"]' function(event) { record(this, event); }); $(document).on('mouseover', '.js-test[data-test-events~="mouseover"]', function(event) { record(this, event); }); ... etc ... </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload