4

I simply want to hide a div, if a text box loses focus, unless, the user clicks in another certain div. If user clicks that particular div, then the focusout doesn't trigger the div.box being hidden.

Below is code with my pseudocode commenting. Any ideas?

textInput.focusout(function() {
    // So long you didn't click div.stop, then
        $('div.box').hide();
});
James
  • 5,942
  • 15
  • 48
  • 72

4 Answers4

4
$(document).bind('click',function(e) {
  if ($(e.target).closest('div.box').length) return;
  $('div.box').hide();
});

Try this!

Luke
  • 11,426
  • 43
  • 60
  • 69
vuong
  • 41
  • 2
3
var flag = false;

$('div.stop').click(function() {flag = true;});
textInput.focusout(function() {
    // So long you didn't click div.stop, then
    if(!flag)
        $('div.box').hide();
});

If you wanted to avoid adding the flag variable, you could use jQuery's .data to store the flag value against e.g. the div.stop element, e.g:

$('div.stop').click(function() {$(this).data('clicked', true);});

// ...

    if(!$('div.stop').data('clicked'))
// ...

EDIT

If you want to allow for the situation where the text box has focus, and you then click on div.stop, and you don't want it to hide, then you could try something like:

$('div.stop').click(function() {$('div.box').stop();});
textInput.focusout(function() {
    // So long you didn't click div.stop, then
    $('div.box').delay(200).hide();
});
sje397
  • 41,293
  • 8
  • 87
  • 103
  • 1
    Hmmm... have you tested it? I think that the text box might lose focus before `click` fires on the button. – Strelok Sep 22 '10 at 06:17
  • I did some modifications to enable it to be fired multiple times in a document, but the general solution you provided was correct. Thanks! – James Sep 22 '10 at 15:46
2
var flag = false;
$('#inputID').blur(function(){
   $('div.box').toggle(flag);       
});

$('#someDIVid').click(function(){
    flag = true;
});

simple demo

added notes:

.toggle( showOrHide )

showOrHide A Boolean indicating whether to show or hide the elements. If this parameter is true, then the matched elements are shown; if false, the elements are hidden.

Reigel Gallarde
  • 64,198
  • 21
  • 121
  • 139
  • There's no point in using toggle here - `if(!flag) ....hide()` is more efficient and easier to read. – sje397 Sep 22 '10 at 06:27
  • @sje397 - I expected someone would say that :) But you were the one to answer first, so I have to think of other ways. What's in my mind is maybe the OP may want to show the box again after clicking another box (`div.stop` on OP) if `div.box` already hidden. :) – Reigel Gallarde Sep 22 '10 at 06:37
0

You can solve this by setting timer on focusout:

$(document).on("focusout", "#textInput", function () 
{
    setTimeout(function ()
    {
        $('div.box').hide();
    }, 101); //I've added 101ms to wait before hiding. (Lower than 80 often fails on my pc)
});
double-beep
  • 5,031
  • 17
  • 33
  • 41
DiegoSnip
  • 1
  • 2