Stopping Propagation

by ChrisStanyon

HTML

<p>You can toggle this by clicking on anything but the ImageButtons</p>
<div class="menu" id="version1">
	<a class="hover-link">BASKET</a>
	<div class="sub">
		<p>The buttons</p>
        <input type="image" name="plus" src="http://lorempixel.com/20/20/sports/1" style="width:20px;" />
        <input type="image" name="minus" src="http://lorempixel.com/20/20/sports/2" style="width:20px;" />
	</div> 
</div>

<p>You can only toggle this by clicking a blank area of the .menu DIV</p>
<div class="menu" id="version2">
	<a class="hover-link">BASKET</a>
	<div class="sub">
		<p>The buttons</p>
        <input type="image" name="plus" src="http://lorempixel.com/20/20/sports/1" style="width:20px;" />
        <input type="image" name="minus" src="http://lorempixel.com/20/20/sports/2" style="width:20px;" />
	</div> 
</div>

CSS

.menu { width: 400px; border: 1px solid green; margin: 20px;  }
.sub { border: 1px solid red; }

JavaScript

//Code to prevent the button from firing the toggle
$('#version1.menu').click(function (e) {
	$('.sub', $('#version1')).slideToggle(400);
});	
$('.sub input[type="image"]', $('#version1')).click(function (e) { e.stopPropagation(); });



//Code to prevent any child from firing the toggle
$('#version2.menu').click(function (e) {
	if (e.target == this) {
		$('.sub', $('#version2')).slideToggle(400);
	}
});