3

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/

Alex B
  • 1,009
  • 3
  • 18
  • 26

3 Answers3

4

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

Balachandran
  • 9,567
  • 1
  • 16
  • 26
  • I thought by triggering a jQuery click that the event's last handler would be the browser's default action. Your solution works but triggering the click on the DOM element directly. Why? – Alex B Dec 19 '14 at 13:18
  • Why use jQuery for some, but not the other? – alex Dec 22 '14 at 05:42
1

Triggering-event-handlers clears about this,

The .trigger() function cannot be used to mimic native browser events, such as clicking on a file input box or an anchor tag. This is because, there is no event handler attached using jQuery's event system that corresponds to these events.

The jQuery UI Team created jquery.simulate.js in order to simplify triggering a native browser event for use in their automated testing. Its usage is modeled after jQuery's trigger.

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

And for your problem you have to use javascript core 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 the answer for the same issue

Community
  • 1
  • 1
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
0

Try this:

$(document).ready(function()
{
    $("#link1").click(function()
    {
      $('#link2')[0].click();
    });
});
Rahul Munjal
  • 2,551
  • 2
  • 15
  • 35