Jquery's .not() and :not doesn't seem to work in this particular scenario. Any corrections or alternatives would be REALLY appreciated!

As you see from the code below, when you click on the green box, the purple box will either slide up or down.

How can I exclude the checkbox from the click area? ie, so that when you click the green box an animation occurs, but not when you click the checkbox..?

<html>
<head>
	<style type="text/css">
	#box {
		width:100px;
		height:100px;
		background-color:green;
	}
	
	#slider {
		width:100px;
		height:100px;
		background-color:purple;
		display:none;
	}
	</style>
	
	<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
	
	<script type="text/javascript">
	$(document).ready(function(){
		$('#box').not(':checkbox').click(function(){
		if ($(this).next('#slider').is(":hidden")) {
			$(this).next('#slider').slideDown('normal');
		} else {
			$(this).next('#slider').slideUp('normal');
		}
		});
	});
	</script>

</head>

<body>
	
	<div id="box">
		<input type="checkbox" />
	</div>
	<div id="slider">
	</div>

</body>
</html>

Recommended Answers

All 3 Replies

Rom,

That's caused by event propagation. In other words, the click is firing a click event in the div underlying the checkbox.

This can't be cured with either not()or :not because it isn't a question of jQuery selection.

Instead, you have to specifically inhibit the click from propagating downwards, like this:

$(document).ready(function(){
	$('#box').click(function(){
		var $s = $(this).next('#slider');
		if ($s.is(":hidden")) { $s.slideDown('normal'); }
		else { $s.slideUp('normal'); }
	});
	$('#box input[type=checkbox]').click(function(evt){
		evt.stopPropagation();
	});
});

Airshow

thanks Airshow!
SOLVED

Heres a lighter version using slidetoggle if anyone ever needs it...

$(document).ready(function(){
        $('#box').bind('click', function(){
            $('#slider').slideToggle();
        });
        $('#box :checkbox').click(function(e) {
            e.stopPropagation();
        });
    });
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.