jQuery: On form input focus, show div. hide div on blur (with a caveat)

Posted by Lyon on Stack Overflow See other posts from Stack Overflow or by Lyon
Published on 2010-03-11T15:53:30Z Indexed on 2010/03/11 17:54 UTC
Read the original article Hit count: 302

Filed under:
|
|

Hi,

I am able to make a hidden div show/hide when an input field is in focus/blur using the following code:

  $('#example').focus(function() {
    $('div.example').css('display','block');
  }).blur(function() {
    $('div.example').fadeOut('medium');
  });

The problem is I want div.example to continue to be visible when the user is interacting within this div. E.g. click, or highlighting the text etc. within div.example. However div.example fades out whenever the input is not in focus and the mouse is interacting with elements within the div.

The html code for the input and div elements is as follows:

<p>
<label for="example">Text:</label>
<input id="example" name="example" type="text" maxlength="100" />
<div class="example">Some text...<br /><br />More text...</div>
</p>

How do I make it such that the div.example only disappears when the user clicks outside the input and/or div.example? I tried experimenting with focusin/focusout to check the focus on <p> but that didn't work either.

Would it matter that div.example is positioned directly below the input field #example using jQuery? The code that does that is as follows:

var fieldExample = $('#example');
$('div.example').css("position","absolute");
$('div.example').css("left", fieldExample.offset().left);
$('div.example').css("top", fieldExample.offset().top + fieldExample.outerHeight());

My apologies if this has been asked before, but the many show/hide div questions I read does not cover this. Thanks for your advice. :)

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about focus