As we know, returning false
from a DOM event handler will stop the propagation of the event. But I recently discovered that the behavior of different elements varies with respect to this event. For example, consider the following:
<div id="container"> <input type="checkbox" name="foo" value="1" /> Check me! <br /> <select> <option>1</option> <option>2</option> <option>3</option> </select> <br /> <input type="text" size="30" /> </div>
The surrounding container has a click handler that returns false:
$('#container').click(function(e) { $('#clicks').append('<span>clicked</span>'); return false; });
Within the div
, I can still click on the text box and enter text, and can still click on the dropdown to change its value. But clicking on the checkbox does nothing (actually, that’s not quite true – it checks the box, fires the handler, then unchecks it). jsfiddle here: http://jsfiddle.net/4ncaq/
This behavior is consistent across browsers so I assume it’s by design. But what exactly is the rule that’s at work here? How can I know how other kinds of elements might behave in this type of scenario?
Advertisement
Answer
When you click an element, the event will continue propagating the event until some handler decides to cancel the propagation. In this case, when you click the checkbox, it will raise the event for the <input>
first and then propagate to #container
where you are stopping propagation.
If you want to cancel the propagation from input elements such as checkboxes or textareas you should bind to their click
event and stop propagation at that point.
Edited
return false
also cancels the default action for the original target element. Checkboxes, links, radio buttons are some of the elements where the default click action is cancelable. The default action for the click event in a checkbox toggles the value of the checkbox while there is no default click action for the select which means it does not get cancelled.
I’ve tried to find a list of default actions without luck but you can check the links at Is there a standard resource for the “default action” of HTML elements?.