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?
This is because of event bubbling Use
$( document ).on( 'click touch', '.rate', function(e) {
alert( $(this).data('rate') );
e.stopPropagation();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With