Andrew
Andrew

Reputation: 20061

CSS input:focus usage

Trying to get a span to display:block when user clicks the text field. But it's not displaying, anybody see the problem with my code?

see fiddle http://jsfiddle.net/WN22k/

CSS

span {
    display:none;
}
input:focus span{
    display:block;
}

HTML

 <div>Password: <input type='password' name='password' maxlength="100"> <span class="help">...password message...</span></input></div>

Upvotes: 0

Views: 945

Answers (3)

michael t
michael t

Reputation: 390

While your mark-up is invalid, I've got a solution that will work. It requires a little jQuery, but is flexible enough to meet your needs:

View fiddle

I've taken the liberty of fixing your HTML:

<label for="password">Password: </label>
<input type="password" class="help" id="password" name="password" maxlength="100" rel="help_password" />
<span id="help_password" class="message">...password message...</span>

To adhere to WCAG standards, your input field requires a correlating label tag. I've also added a rel attribute which the value should match an ID tag of the corresponding help message's ID attribute.

And with a tiny bit of jQuery:

$(document).ready(function(event) {
    $('input.help').focus(function(event) {
    $('#' + $(this).attr('rel')).show();
});    
$('input.help').blur(function(event) {
    $('#' + $(this).attr('rel')).hide();
   }); 
});

You can auto-toggle the help message for any field that has the class "help" and a corresponding help message span tag.

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324600

As Chris says, you can't have children of <input> elements.

Try this instead:

HTML:

<div>Password:
    <input type="password" name="password" maxlength="100" />
    <span class="help">...password message...</span>
</div>

CSS:

.help {display:none}
input:focus~.help {display:block}

Note that you might want display:inline or display:inline-block, depending on what you're doing.

Upvotes: 5

Mister Epic
Mister Epic

Reputation: 16713

Spans can't be a child element of an input, your markup is invalid.

Often if you're adding some sort of contextual message, you could either:

A) Add it as the value of the input, and then clear it with javascript as soon as the input gets focus

B) Write the message just off to the side or as a tooltip

Upvotes: 1

Related Questions