How to make a click shoot another click?

Asked

Viewed 25,431 times

9

I wonder if there’s a way to click on an element by clicking on another place, something like this:

jQuery

$("#button1").click(function(){
    $("#button2").click();
});

I tried that and it didn’t work.
Taking the example Ids as real; there are many events attached to the #button2 and I believe the most practical way to fire them when you click the #button1 that’s the way it is, because I can’t internally touch these events or link them to the #button1.

  • 3

    Have you tried using the function trigger? Staying $('#button2').trigger('click');. Take a look at http://api.jquery.com/trigger/

  • @Would Wakim rather post as an answer? When I posted your comment, it had not yet appeared to me.

  • @Bacco, I’m not sure if this is the solution. I say this because the $(...).click is a shortcut to the trigger('click') (http://stackoverflow.com/questions/9666471/jquery-advantages-differences-in-trigger-vs-click). Maybe the problem could be in the bind of the event (click vs on).

  • 1

    Need not, can leave the answer.

1 answer

17


$("#button1").click(function(){
    $("#button2").trigger('click');
});

Source: http://www.theextremewebdesigns.com/blog/jquery-trigger-click-trigger-method-binded-to-click-event-example/

Alternative using .on with delegation:

$("#divQueContemOsBotoes").on( "click", "#button1", function() {
    $("#button2").trigger('click');
});


Demonstration:

$("#button1").click(function(){
  $("#button2").trigger('click');
});

$("#button2").click(function(){
  $("#box").append('<p>Botao 2 clicado</p>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="box">
  <button id="button1">Botao 1</button>
  <button id="button2">Botao 2</button>
</div>

  • 1

    Ah, my fault, I wrote the click of on no quotes. It worked perfectly, thank you, anyway. Just to know, in place of the #divQueContemOsBotoes I can put another element like html or body (I know it’s possible, because I did it and it worked, but what I really want to know is if this could be a problem in the future)?

  • 2

    @Patrick can, but the more "close" to the desired object, the less event propagations will be processed, because if you put in html, any click anywhere will have to be analyzed to see if it matches the filter or not. Try to get the nearest div that will contain the button in its original layout, for JS to process less information.

  • The demo link is offline. Could make the simulation of this behavior?

  • 2

    @Eduardoseixas done, grateful for the warning.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.