Clicking on one button to trigger click event on another

Yarin picture Yarin · Dec 20, 2013 · Viewed 45k times · Source

I want to click on button 2 to trigger a click event on button 1.

However, when I try the following, nothing happens when clicking on #2: no alert for #1 or #2.

HTML:

<div id="container">
<button id="button-1">Button 1</button>
<button id="button-2">Button 2</button>
</div>

JS:

$('#container').on( "click", '#button-1', function(e){
    alert('CLICKED 1');
});
$('#container').on( "click", '#button-2', function(e){
    $('#button-1').trigger(e);
    alert('CLICKED 2');
});

http://jsfiddle.net/8RnBf/7/

Moreover, if I put the #2 alert before the trigger, I end up with an infinite loop.

http://jsfiddle.net/8RnBf/6/

Why is this not working as expected?


UPDATE:

I should have made it clear: the original event must be passed. In essence, we're trying to do what was done here, but with delegated events

Answer

Venkata Krishna picture Venkata Krishna · Dec 20, 2013

Use

$('#button-1').trigger('click');

or

$('#button-1').trigger(e.type);

http://jsfiddle.net/8RnBf/17/

instead of

$('#button-1').trigger(e);

JSFIDDLE DEMO

Read about jquery .trigger() here