Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery trigger('click') problem

Tags:

jquery

I have clickable row, that will fire link onclick event, but trigger() cause a new click event on tr.clickable and go into loop. How to prevent this ?

<table>
    <tr class="clickable">
        <td>Test row</td>
        <td><a href="#" onclick="alert('click');" class="trigger"></a></td>        
    </tr>
</table>

js:

$('tr.clickable').click(function(){
    var trigger = $(this).find('a.trigger');
    trigger.trigger('click');
});

Live demo here.

like image 319
marioosh Avatar asked Mar 23 '26 21:03

marioosh


2 Answers

This is down to event bubbling in JavaScript. It's a bit of a weird setup you've got at the moment, but one way to fix it would be to stop the click event bubbling on the a tag:

$('tr.clickable a').click(function (e) {
    e.stopPropagation();
});

Fiddle

Alternately you could not fire the click trigger if the target event is the same element:

$('tr.clickable').click(function(e){
    var trigger = $(this).find('a.trigger').not(e.target);
    trigger.trigger('click');
});

Fiddle

The best way would probably be the first solution, I guess.

like image 175
Matt Avatar answered Mar 25 '26 10:03

Matt


remove trigger.trigger('click'); and thats it :)

like image 41
simoncereska Avatar answered Mar 25 '26 12:03

simoncereska



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!