I am using the following Vanilla binding in order to simulate the jQuery delegation event:
document.addEventListener('click', function(e) {
console.log("some element was clicked");
console.log(e.target);
//here's where I would filter by target
});
It is all working fine except when I try to trigger with jQuery a click event on a link element <a href="#">
. Then it won't work at all. The vanilla click event handler won't be triggered.
Reproduction working on <b>
element
$('button').click(function() {
$('ul').append('<li><b>New</b></li>');
});
document.addEventListener('click', function(e) {
console.log("some element was clicked");
console.log(e.target);
});
$(document).on('keydown', function(){
console.warn("-------Trigger--------")
$('li').find('b').trigger('click');
});
div{
background: yellow;
padding:10px 20px;
border: 1px solid #ccc;
margin: 10px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Add element</button>
<span id="trigger">Trigger</span>
<div>
Just focus the white panel and press any key. That will trigger the jQuery.click() event as you can see in the code.
</div>
<ul>
<li>Old element</li>
<li>Old element</li>
<li><b>Old element</b></li>
</ul>
Instead, if I replace the link element for a bold one <b>
it works as expected.
What's going on?
Reproduction not working on <a>
element
$('button').click(function() {
$('ul').append('<li><a href="#">New</a></li>');
});
document.addEventListener('click', function(e) {
console.log("some element was clicked");
console.log(e.target);
});
$(document).on('keydown', function(){
console.warn("-------Trigger--------")
$('li').find('a').trigger('click');
});
div{
background: yellow;
padding:10px 20px;
border: 1px solid #ccc;
margin: 10px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Add element</button>
<span id="trigger">Trigger</span>
<div>
Just focus the white panel and press any key. That will trigger the jQuery.click() event as you can see in the code.
</div>
<ul>
<li>Old element</li>
<li>Old element</li>
<li><a href="#">Old element</a></li>
</ul>
And no, I do not want to use [0]
like this:
$('li').find('a')[0].click();
I want it to fire normally:
$('li').find('a').click();
Unfortunately, you cannot trigger native click handlers in jQuery on links, it is disabled in the source and a comment says "For cross-browser consistency, don't fire native .click() on links".
So, you will either have to bind the document click handler using jQuery $(document).on("click")
or call the nodes clickHandler directly $('li').find('a')[0].click();