Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger only clicked event in nested elements

I have the following setup to display rating stars:

$( document ).on( 'click touch', '.rate', function() {
   alert( $(this).data('rate') );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    <span class="rate" data-rate="1">1
        <span class="rate" data-rate="2">2
             <span class="rate" data-rate="3">3
                 <span class="rate" data-rate="4">4
                     <span class="rate" data-rate="5">5
                    </span>
                </span>
            </span>
        </span>
    </span>

If you click on a higher number than 1, you will trigger multiple events.

The reason is clearly because of the nested elements. My question is, how can I make it so when user clicks on a number, it only triggers that event... without changing the HTML?

like image 499
Henrik Petterson Avatar asked Dec 17 '25 17:12

Henrik Petterson


1 Answers

This is because of event bubbling Use

$( document ).on( 'click touch', '.rate', function(e) {
   alert( $(this).data('rate') );
   e.stopPropagation();
});
like image 90
Farhan Haque Avatar answered Dec 19 '25 13:12

Farhan Haque



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!