How do I manually trigger a delegated event with jQuery? How do I manually trigger a delegated event with jQuery? jquery jquery

How do I manually trigger a delegated event with jQuery?


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/


I know, this question is ancient but as I was stumbling over it while looking for an answer to another problem I thought I might as well share my slightly simpler approach here.

The idea is to simply create the event on the desired target element directly: $(target_selector).trigger(event_type) or - even shorter for standard events like "click" - do $(target_selector).click(), see my little fiddle below:

$(function(){ $('.container').on('click','button',function(){  console.log('delegated click on '+$(this).text());  return false; }); $('#other').click(e=>$('.container button').trigger('click')); $('#clickone').click(e=>$('.container .one').click());});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><form class="container"><button type="submit" class="one">click 1</button> and another chance to click here on <button class="two">click 2</button>.</form><br><div id="other">Trigger clicks on both buttons here!</div><br><div id="clickone">Trigger a click on button "one" only.</div>