0
$(document).ready(function () {
    $(".btn-slide").focus(function () {
        $("#moresearch").show("fast");
        $(".btn-slide").blur(function () {
            $("#moresearch").hide("fast");
        });
    });
});

In this sample .btn-slide is my textbox. When it is focused the moresearch div is shown. When it is blured that div hides.

The problem is that when I click on the moresearch div, the div closes, but it should only close when one clicks outside.

Daniel
  • 23,129
  • 12
  • 109
  • 154

2 Answers2

3

First of all, why are you nesting the focus and blur event bindings? That way, the 'blur' gets bound every time the 'focus' event is fired (but it won't be unbound). But that's not the problem here.

One possible solution would be to check for the element the focus went to in the blur callback. Have a look at When onblur occurs, how can I find out which element focus went *to*? for information on how to do that.

Maybe something like that:

$(".btn-slide").blur(function(event) {
    var target = event.explicitOriginalTarget||document.activeElement;
    if (target != $("#moresearch")[0]) {
        $("#moresearch").hide("fast");
    }
}

Edit: Or rather this might to the trick:

if (!$("#moresearch").has($(target)) > 0 &&! $("#moresearch")[0] == target)

This will check where the focus left and whether this is the target div or one of it's children. Have not tried it.

Community
  • 1
  • 1
sudoremo
  • 2,274
  • 2
  • 22
  • 39
0

Try this:

$(document).ready(function () {
    $(".btn-slide").focus(function () {
        $("#moresearch").fadeIn("fast");
        $('body').not('.btn-slide').click(function () {
            $("#moresearch").fadeOut("fast");
        });
    });
});

Note: Use fadeIn() and fadeOut instead show/hide when you want to do action with animation.

Barlas Apaydin
  • 7,233
  • 11
  • 55
  • 86
  • This will work, but only if the input element is left by clicking somewhere else. But if it's left for instance by pressing the *tab* key, this would not work, would it? – sudoremo Aug 09 '12 at 09:54
  • yeap, this won't work with tab key.. your answer is much more solid. – Barlas Apaydin Aug 09 '12 at 09:54