Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I trigger the default href on another anchor with JS?

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/

like image 257
Alex B Avatar asked Dec 06 '25 09:12

Alex B


1 Answers

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();

like image 198
Balachandran Avatar answered Dec 07 '25 23:12

Balachandran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!