Reputation: 26993
So it's kind of hard to put into a sentence but here is a simple example:
<html>
<head>
<title>Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
<!--
$(document).ready(function() {
$("#input").focus(function() {
$("#p").show();
}).blur(function() {
$("#p").hide();
});
$("#p").click(function() {
alert("Thanks for clicking me");
});
});
-->
</script>
</head>
<body>
<input type="text" id="input" />
<p id="p" style="background:red;display:none"">
Click me.
</p>
</body>
</html>
Basically when you focus on an input a paragraph appears and when the focus is blurred the paragraph disappear. However there is also a click listener on the paragraph so when you click it an alert messagebox appears. The problem is when I focus the input box the paragraph appears [expected] but when I click on the paragraph the blurring of the input box is registered first so the paragraph is hidden before the browser detects I clicked on it.
Upvotes: 2
Views: 1021
Reputation: 25620
Try Ben Alman's jQuery Outside events plugin
Then your code would be:
$(document).ready(function() {
$("#input").focus(function() {
$("#p").show();
}).bind('focusoutside', function(event) {
if (!$(event.target).is('#p')) {
$("#p").hide();
}
});
$("#p").click(function() {
alert("Thanks for clicking me");
// Do this if you need to hide #p after doing
// whatever click on p really does.
$(this).hide();
});
});
By using the focusoutside event it will capture both clicking and tabbing away from #input
and will let you decide based on where the focus went want to do.
Example: http://jsfiddle.net/petersendidit/WSEWh/2/
Upvotes: 2