Clicking on one button to trigger click event on another
Asked Answered
M

3

8

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

Musty answered 20/12, 2013 at 16:32 Comment(0)
C
10

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

Carlotacarlotta answered 20/12, 2013 at 16:34 Comment(4)
The OP is already passing a click event object to trigger, I don't think this is the issue.Coyote
No, we need to pass the orig event, sorry that wasn't made clearMusty
@RoryMcCrossan - or event.type can also be used to trigger it.Carlotacarlotta
@Musty - use e.type to trigger the original event.Carlotacarlotta
W
4

To properly trigger a delegated event you have to create an event object and pass it to trigger()

$('#container').on( "click", '#button-2', function(e){
    var event = jQuery.Event(e.type);
    event.target = $('#button-1').get(0);

    $('#container').trigger(event);
});

FIDDLE

That way you're actually triggering the event on the element it was bound to, passing the selector the delegated event handler will filter on as the event.target, so it will fire just as it would if the element was actually clicked.

Or you could use the original event if you change the event.target

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

$('#container').on( "click", '#button-2', function(e){
    e.target = $('#button-1').get(0);
    $('#container').trigger(e);
});
Whitefaced answered 20/12, 2013 at 16:37 Comment(0)
S
3

When you need to call click event of any button then syntax is as below

$('selector').trigger(event);

selector -> which tag's event you need to fire

event -> which event you need to fire

In your case you need to change following one line

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

here you need pass event of e like click event, select event, etc.

so solution is replace this line with any of the following line

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

$('#button-1').trigger("click");
Subgenus answered 22/4, 2015 at 19:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.