Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I manually trigger a delegated event with jQuery?
    text
    copied!<p>Is there a way with jQuery to manually trigger an delegated event handler? </p> <p>Take following example code:</p> <pre><code>&lt;div class="container"&gt; &lt;input type="button" value="Hello"&gt; &lt;span class="output"&gt;&lt;/span&gt; &lt;/div&gt; ​ &lt;script&gt; $('.container') .on('click', '[type=button]', function(e) { $(e.delegateTarget).find('.output').text($(this).val()); }) .find('[type=button]').triggerHandler('click');​ &lt;/script&gt; </code></pre> <p>(Online: <a href="http://jsfiddle.net/TcHBE/">http://jsfiddle.net/TcHBE/</a>)</p> <p>I was expecting that this would work, and text "Hello" would appear in the span without actually clicking the button, but it doesn't.</p> <p>I'm using <code>e.delegateTarget</code> inside the handler, because the <code>.ouput</code> element won't be in a known relationship to the button, other than some place inside the <code>.container</code>. That is why I'm using a delegated event handler in the first place.</p> <p><strong>Update:</strong></p> <p>Also I'm using <code>triggerHandler</code>, because the event has a default behaviour in the real code I don't want to trigger. (In the real code the event is the custom event <code>hide</code> of the <a href="http://twitter.github.com/bootstrap/javascript.html#modals">Bootstrap Modal plugin</a>, but I don't actually want to hide the modal when triggering the event handler on page load).</p> <p>I could extract the handler into a named function and call it directly, but due to the use of <code>e.delegateTarget</code>, that would make the how construct more complicated.</p>
 

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