How do I manually trigger a delegated event with jQuery?

jquery

Solution

You could create an Event object manually and set the `target` property accordingly to trick jQuery into thinking the event bubbled up.

var c = $('#container');

c.on('click', '[type=button]', function(e) {
    $(e.delegateTarget).find('span').text($(this).val());
});

var event = jQuery.Event('click');
event.target = c.find('[type=button]')[0];

c.trigger(event);

http://jsfiddle.net/PCLFx/

Problem

Is there a way with jQuery to manually trigger an delegated event handler? Take following example code: ``` <div class="container"> <input type="button" value="Hello"> <span class="output"></span> </div> ​ <script> $('.container') .on('click', '[type=button]', function(e) { $(e.delegateTarget).find('.output').text($(this).val()); }) .find('[type=button]').triggerHandler('click');​ </script> ``` (Online: http://jsfiddle.net/TcHBE/) I was expecting that this would work, and text "Hello" would appear in the span without actually clicking the button, but it doesn't. I'm using `e.delegateTarget` inside the handler, because the `.ouput` element won't be in a known relationship to the button, other than some place inside the `.container`. That is why I'm using a delegated event handler in the first place. Update: Also I'm using `triggerHandler`, 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 `hide` of the Bootstrap Modal plugin, but I don't actually want to hide the modal when triggering the event handler on page load). I could extract the handler into a named function and call it directly, but due to the use of `e.delegateTarget`, that would make the how construct more complicated.

Original source