Note that there are some explanatory texts on larger screens.

plurals
  1. POCan I get usable data in a jQuery live handler for a custom event?
    text
    copied!<p>jQuery now allows you to use <a href="http://docs.jquery.com/Events/live" rel="nofollow noreferrer">live</a> to handle custom events, something I've used in my latest project and found very handy. I have come up against a limitation/bug, however, that I'm hoping someone will be able to help me with.</p> <p>When you trigger an event, you can pass additional array of data too, like this:</p> <pre><code> $(this).trigger('custom', ['foo', 'bar' ]); </code></pre> <p>If you were just using <a href="http://docs.jquery.com/Events/bind" rel="nofollow noreferrer">bind</a>, you could absolutely access these variables. However, if you're using live, it turns out that you have no access to data <strong>as far as I can tell</strong>. Am I wrong? Is there another way?</p> <p>Here is some demo code to illustrate:</p> <pre><code> $().ready(function() { $('button').click(function(){ $('&lt;li&gt;Totally new one&lt;/li&gt;').appendTo('ul'); }); $('li').bind('custom', function(e, data) { // this one works fine for old elements, but not for new ones $('#output1').text('Bind custom from #' + e.target.id + '; ' + data); }).live('custom', function(e, data) { // this one triggers for old and new elements, but data is useless $('#output2').text('Live custom from #' + e.target.id + '; ' + data); }).live('click', function(){ $('div').text(''); // just using click count to illustrate passing data in the trigger var clicks = $(this).data('clicks'); if(typeof clicks == 'undefined') clicks = 1; $(this).trigger('custom', ['Times clicked: ' + clicks ]).data('clicks', clicks + 1); }); }); </code></pre> <p>And the related HTML:</p> <pre><code>&lt;button&gt;Add&lt;/button&gt; &lt;ul&gt; &lt;li id="one"&gt;First Item&lt;/li&gt; &lt;li id="two"&gt;Second Item&lt;/li&gt; &lt;li id="three"&gt;Third Item&lt;/li&gt; &lt;/ul&gt; &lt;div id="output1"&gt;Result 1&lt;/div&gt; &lt;div id="output2"&gt;Result 2&lt;/div&gt; </code></pre>
 

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