Why can't I run the default href on a different anchor with JS?

I am posting this because I cannot find the same question elsewhere.

I'm trying to call the default anchor action, but I'm calling .click () or .trigger ('click') in the click handler of another anchor.

Same:

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 when pressed. Is it something that's locked down for security or accessibility?

I don't want to use window.open ();

script: http://jsfiddle.net/0hggdkzb/

+3


source to share


3 answers


try

jQuery(document).ready(function(){
    $('#link1').on('click', function(){
      // $('#link2').click().css('color','red');
        document.getElementById("link2").click();
    });
});

      

DEMO



or

you can call event $('#link2')[0].click();

+4


source


Triggering-event-handlers clears up about this,

The .trigger () function cannot be used to simulate native browser events, such as clicking on a file input field or an anchor tag. This is because when using the jQuery event, there is no event handler that matches those events.

The jQuery UI team created jquery.simulate.js to make it easier to fire their own browser event for use in their automated testing. Its use is simulated after jQuery has started.

$( "a" ).simulate( "click" );

      

And for your problem you have to use the main javascript event as @Bala answered like,



$(function(){
    $('#link1').click(function(){
        $('#link2')[0].click();
    });
});

      

or use location.href like,

$(function(){
    $('#link1').click(function(){
        window.location = $('#link2').attr('href');
    });
});

      

Also, Hoffman gave an answer to the same problem

+1


source


Try the following:

$(document).ready(function()
{
    $("#link1").click(function()
    {
      $('#link2')[0].click();
    });
});

      

0


source







All Articles