John Stephens
John Stephens

Reputation: 811

Jquery: How do I set a hidden element to display when another element is in focus?

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!

Upvotes: 3

Views: 19141

Answers (3)

doublejosh
doublejosh

Reputation:

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

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

Upvotes: 0

TStamper
TStamper

Reputation: 30374

Updated with blur event for you

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

  });   

Upvotes: 9

eKek0
eKek0

Reputation: 23319

Use the focus event.

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

Upvotes: 1

Related Questions