Angry Coder Angry Coder - 4 months ago 17
jQuery Question

Why onclick is being triggered twice?

This is a small piece of code on which I have been working:

All I want is to add an

active
class to label on click of the same element and leave the default behavior same.

I don't know why is the click event being triggered twice ??



$('label.add-to-favourite').click(function(e){
alert("here");
$(this).toggleClass('active');
});

.add-to-favourite span{
cursor: pointer;
color: #d2d6de;
}


.add-to-favourite:hover span, .add-to-favourite.active span {
color: #CB3D3D;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/>

<ul>
<li>
<label class="add-to-favourite">
<span class="fa-stack fa-lg">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-heart fa-stack-1x fa-inverse" title="Add to Favourites" data-toggle="tooltip"></i>
</span>
<input type="checkbox" name="favourites[]" value="1">
</label>
</li>
<li>
<label class="add-to-favourite">
<span class="fa-stack fa-lg">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-heart fa-stack-1x fa-inverse" title="Add to Favourites" data-toggle="tooltip"></i>
</span>
<input type="checkbox" name="favourites[]" value="2">
</label>
</li>
</ul>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>




Answer

When you click on the label, it triggers the checkbox`s click event.

But clicking on a label also automatically sends a click event to the associated input element, so this is treated as a click on the checkbox. Then event bubbling causes that click event to be triggered on the containing element, which is the label, so your handler is run again.

put the checkbox outside the label like so

<label></label>
<input type="checkbox">

UPDATE : you can also do as @Rejith R Krishnan suggested and set the click event handler on the checkbox and not the label