How do I manually trigger a delegated event with jQuery?
We can pass an additional event configuration
to jQuery's $.Event()
as the second argument
. More information here.
$('#click-me').on('click', function(evt){
$(document).trigger($.Event('custom-click', {target: evt.currentTarget}));
});
$(document).on('custom-click', '#click-me', function(evt){
alert(`${evt.type} was triggered on button with ${evt.target.id} id.`);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="click-me">Click Me</button>
Good Luck...
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>
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/