0

Say I have 2 links a1 and a2, and a2 is hidden. When the user clicks on a1, I want to simulate the clicking of a2. How can this be done with jQuery?

Prabhu
  • 12,995
  • 33
  • 127
  • 210

3 Answers3

10

It depends on what you mean by "simulate the clicking of a2".

Assuming that a1 and a2 are ID attributes, if you mean that you want to trigger the jQuery handler on that element, you can do this:

$("#a1").click(function(){ 
    $("#a2").trigger('click'); 
});

If you want to trigger it without bubbling the event or triggering the default behavior, do this:

$("#a1").click(function(){ 
    $("#a2").triggerHandler('click'); 
});

But if you wanted to actually visit the associated href location, you would need this:

$("#a1").click(function() { 
    window.location = $("#a2").attr('href'); 
});

or

$("#a1").click(function() { 
    window.location = document.getElementById('a2').href; 
});
user113716
  • 318,772
  • 63
  • 451
  • 440
6
$("#a1").click(function(){ $("#a2").click(); });
hunter
  • 62,308
  • 19
  • 113
  • 113
0

The other answers cover your options as far as solutions go, but to improve your understanding of how jQuery works particular regarding event binding for clicks, I recommend looking over the jQuery API documentation for click().

calvinf
  • 3,754
  • 3
  • 28
  • 41