views:

2757

answers:

3

Hi! I'm trying to display contextual help alongside form fields, that is only visible when those fields are in focus or hovered over. I've tried using mere CSS, but the results seem very fragile and inconsistent.

Here is my CSS:

form .instruct {
 position: absolute;
 right: -220px;
 top: 10px;
 visibility: hidden;
 width: 200px;
 z-index: 1000;
}
form li:focus .instruct, form li:hover .instruct {
 visibility: visible;
}

In my markup, I've given my form some structure using an ordered list, grouping each field with it's instructions in a li element:

<form>
 <ol>
  [...]
  <li>
    <label for="message">Message</label>
    <textarea id="message" name="message"></textarea>
    <div class="instruct">
     <p>Instructional text and <a href="#">Formating help.</a></p>
    </div>
  </li>
  [...]

The instructions appear when hovering over the field, but not when the field is in focus-- and if the mouse moves to select a link in the contextual instructions, they disappear.

Each field has it's own instructions, and I need each one to appear when the appropriate field is in focus or hover state.

I thought this might be a case where jquery could make life easier. Is there a quick way to accomplish this? If there's a reliable way to do this using raw CSS, I'd be happy with that too.

Thanks!

+4  A: 

Updated with blur event for you

   $(function()
   {
        $('.instruct').hide(); //hide 
        $('#message').focus(function(){  
            $('.instruct').show(); //show
        }).blur(function(){  
            $('.instruct').hide(); //hide again
        });

  });
TStamper
Thanks-- this is almost what I need!But each field has it's own instructions, grouped with it in an li element. Using this script brings them ALL into focus when #message is selected.Is there a way to make it more generic, so that when each li is in focus or hover, the instructions *within* that li are visible?This script also gets rid of my hover visibility.Thank you again for your help!
John Stephens
How about hiding them when they are no longer in focus?
John Stephens
for that you can just identify each instruction as unique names, in this example, unique class names and follow the same criteria and to the second comment the blur event does that
TStamper
Awesome. The only problem I had was that using .hide made the instruction links unclickable-- as soon as you click outside the field, even a link, it lost focus and disappeared. I used .fadeOut(1000) instead of hide and the links got clickable again. Thanks for your help!
John Stephens
+1  A: 

Use the focus event.

The focus event fires when an element receives focus either via the pointing device or by tab navigation.

eKek0
John Stephens
A: 

I've found the jQuery toggle() to be the solution I wished I'd used.

http://docs.jquery.com/Effects/toggle