I'm posting this because I can't find the same question elsewhere.
I'm trying to trigger the default action of an anchor but calling .click() or .trigger('click') in the click handler of another anchor.
Like so:
HTML:
<!-- I want to simulate a user clicking link2 when the user actually clicks link 1. -->
<!-- My guess is that triggering click just triggers any JS-bound click handlers. But that would defeat the point of e.preventDefault() when you usually have to call this to stop the default href being followed -->
<a id="link1" href="#">Click</a>
<a id="link2" target="_blank" href="http://google.com">Link 2</a>
JS:
$(document).ready(function(){
$('#link1').on('click', function(){
$('#link2').click();
$('#link2').trigger('click'); // Neither work
});
});
I feel like such a noob but nothing happens on click. Is this something that is blocked for security or accessibility?
I do not want to use window.open();
fiddle: http://jsfiddle.net/0hggdkzb/
try
jQuery(document).ready(function(){
$('#link1').on('click', function(){
// $('#link2').click().css('color','red');
document.getElementById("link2").click();
});
});
DEMO
Or
you can trigger event $('#link2')[0].click();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With