Reputation: 5642
How can I listen to a change
event on a checkbox without triggering a click
event on its container?
<label><input type="checkbox"> Hello world</label>
I want to trigger an action on the checkbox's change
event, but I don't want it to bubble up to a click
event on the label.
(function ($) {
$('input').change(function (v) {
v.stopPropagation();
});
$('label').click(function () {
alert('You should not see this message if you click the checkbox itself!');
});
})(jQuery);
Any ideas? Thanks!
Upvotes: 1
Views: 2592
Reputation: 105
With plain javascript you can do something like this:
var stopPropagation = false;
selector.addEventListener('mousedown', function(event) {
// simulating hold event
setTimeout(function() {
stopPropagation = true;
// do whatever you want on the `hold` event
})
}
selector.addEventListener('click', function(event) {
if (stopPropagation) { event.stopPropagation(); return false; }
// regular event code continues here...
}
Since mousedown
and click
events are overlapping, we want the click
event to not be triggered when we are trying to get the hold
state. This little helper flag variable stopPropagation
does the trick.
Upvotes: 0
Reputation: 4755
The issue is that two events are triggered when you click the checkbox -- a change
and a click
. You're only catching the change
, so the click isn't ever being told to stop propagation. You need to either add a second handler on the checkbox for click events, or combine one handler to catch both types, like this:
$('input').on('change, click', function (v) {
v.stopPropagation();
});
Here's a jsFiddle demonstrating a combined handler: http://jsfiddle.net/r49PA/4/
Upvotes: 2
Reputation: 38102
You can stop propagation on click
event instead of change
event since you bind click
event for the parent label
:
$('input').click(function (v) {
v.stopPropagation();
});
Upvotes: 1