Ask the CSS Guy

Form field hints with CSS and JavaScript

My co-workers pointed out a nice effect on the Vox registration form. As you tab through each input field, some helper text appears in box out to the right. Try it out. Update (4/20/2007): It has been pointed out that Vox has changed their form, and it no longer uses this effect.

Vox Registration Form

It's a basic example of how helpful a little JavaScript and CSS can be in a form. Instead of the input hints always showing and potentionally cluttering a very simple form, only the hint for the currently focused input will show. This article will show a way to do this.

The HTML

We'll start with a simple form. Vox's form used a definition list to mark up the form, and I'll be doing the same. I place the label in the <dt> tag, and the field in the <dd> tag, like so:

<dl>
  <dt>
    <label for="firstname">First Name:</label>
  </dt>
  <dd>
    <input
      name="firstname"
      id="firstname"
      type="text" />
  </dd>
  ...
  more <dt>'s and <dd>'s
  ...
</dl>

Immediately after each input field, add a span with a class of hint and create a hint for each input, like so:

<dl>
  <dt>
    <label for="firstname">First Name:</label>
  </dt>
  <dd>
    <input
      name="firstname"
      id="firstname"
      type="text" />
    <span class="hint">Use your real name!</span>
  </dd>
  ...
  more <dt>'s and <dd>'s
  ...
</dl>

View what we have so far - an unstyled form.

Some CSS

Let's give this form some style. Assign our form-encompassing <dl> a fixed width and a position of relative. (This is important because our hints will be absolutely positioned relative to the containing <dl> rather than the <body>). Additionally, we'll style the <dt> and <dd> so that the form takes some shape.


dl {
  position: relative;
  width: 350px;
}
dt {
  clear: both;
  float:left;
  width: 130px;
  padding: 4px 0 2px 0;
  text-align: left;
}
dd {
  float: left;
  width: 200px;
  margin: 0 0 8px 0;
  padding-left: 6px;
}

It's coming along. It's time to style the hints. Let's add the following to the CSS.

.hint {
  position: absolute;
  right: -250px;
  width: 200px;
  margin-top: -4px;
  border: 1px solid #c93;
  padding: 10px 12px;
  background-color: #ffc;
}

See how it looks. All the hints are absolutely positioned, and their padding and containing content cause each of them to overlap a little. That's ok, because we'll only be showing one at a time. Add "display:none;" to the CSS.

.hint {
  display:none;
  position: absolute;
  right: -250px;
  width: 200px;
  margin-top: -4px;
  border: 1px solid #c93;
  padding: 10px 12px;
  background-color: #ffc;
}

Now that our form is styled and our hints are hidden, it's time for JavaScript.

The JavaScript

I am going to prepare the input fields so that as focus is put on them, their corresponding hint appears. I do this preparation on page load, using "addLoadEvent", because that's how I roll.

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

function prepareInputsForHints() {
  var inputs = document.getElementsByTagName("input");
  for (var i=0; i<inputs.length; i++){
    inputs[i].onfocus = function () {
      this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
    }
    inputs[i].onblur = function () {
      this.parentNode.getElementsByTagName("span")[0].style.display = "none";
    }
  }
}
addLoadEvent(prepareInputsForHints);

The function prepareInputsForHints looks for all <input> tags and cycles through them. When there is focus on that input field, we grab the first span tag in the <dd> in which the <input> resides, and we change it's display to inline so that it'll show up.

To keep things simple, I've assumed that there is only one <span> tag next to each <input> tag.

What about <select>'s? We need to duplicate the logic we applied to the <input>'s so that it will work with <select>'s, too.

function prepareInputsForHints() {
  var inputs = document.getElementsByTagName("input");
  for (var i=0; i<inputs.length; i++){
    inputs[i].onfocus = function () {
      this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
    }
    inputs[i].onblur = function () {
      this.parentNode.getElementsByTagName("span")[0].style.display = "none";
    }
  }
  var selects = document.getElementsByTagName("select");
  for (var k=0; k<selects.length; k++){
    selects[k].onfocus = function () {
      this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
    }
    selects[k].onblur = function () {
      this.parentNode.getElementsByTagName("span")[0].style.display = "none";
    }
  }
}
addLoadEvent(prepareInputsForHints);

Check out what we have. It's functioning, for all inputs and selects, and it's looking pretty good. There are still a couple of things we can do to help it, though.

Minor Tweaking

Right now the hint is just in a box. Notice how in Vox's example, their hint box has a little arrow attached to it. Let's add that pointer in there. We want an image that has the same border and fill as the hint box, with the exception of the left border, which we don't want to exist. I'm going to use the same one Vox uses - a simple triangle.

pointer

This image will be added as a background image with the help of an additional span, which we need to insert within the hint in the HTML, and give a class of hint-pointer.

<span class="hint">Use your real name!
  <span class="hint-pointer">&nbsp;</span>
  </span>

Let's style it so that it looks like it's part of the hint box.

.hint .hint-pointer {
    position: absolute;
    left: -10px;
    top: 5px;
    width: 10px;
    height: 19px;
    background: url(pointer.gif) left top no-repeat;
}

That's better.

Also, up to this point, we've assumed that every <input> will have a corresponding hint. What if we don't need hints for some of those inputs? Who needs a hint for a field like "First Name"? We also don't want to show hints with submit buttons (remember, they are <input>'s, too!)? As of now, if there is a missing hint, a JavaScript error is returned.

There is more than one way to account for this. Here's one. Let's add some logic to the JavaScript that checks to see if a span exists before trying to change the style of that span.

function prepareInputsForHints() {
  var inputs = document.getElementsByTagName("input");
  for (var i=0; i<inputs.length; i++){
    if (inputs[i].parentNode.getElementsByTagName("span")[0]) {
      inputs[i].onfocus = function () {
        this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
      }
      inputs[i].onblur = function () {
        this.parentNode.getElementsByTagName("span")[0].style.display = "none";
      }
    }
  }
  var selects = document.getElementsByTagName("select");
  for (var k=0; k<selects.length; k++){
    if (selects[k].parentNode.getElementsByTagName("span")[0]) {
      selects[k].onfocus = function () {
        this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
      }
      selects[k].onblur = function () {
        this.parentNode.getElementsByTagName("span")[0].style.display = "none";
      }
    }
  }
}
addLoadEvent(prepareInputsForHints);

I'd love to see other examples of similar effects. Let me know of any you like.

April 3, 2007: textarea example provided

April 3, 2007: Fixed IE6 bug.

It was pointed out that IE6 was showing some buggy behavior the first instance of showing the hints. The border wasn't completely being drawn around the span. I was going to pass it off as "buggy IE6", because I couldn't find a fix, but thanks to David Carriger in the comments, I think we found something.

In the .hint CSS, we have been giving span.hint a background color using "background-color:#ffc", but if we go ahead and give it a background image, too, IE6 will render span.hint properly.

.hint {
  display:none;
  position: absolute;
  right: -250px;
  width: 200px;
  margin-top: -4px;
  border: 1px solid #c93;
  padding: 10px 12px;
  background: #ffc url(pointer.gif) no-repeat -100px -100px;
}

Note that I gave it the same background image as the .hint-pointer span (less overhead that way), and positioned it with a negative margin so that it doesn't actually show up. This is now fixed in the final example and downloadable zip.

See final example, which only shows hints for username and password (and fixes the IE6 bug!).

April 20, 2007): Vox.com, the site whose registration form this article is based on, has changed that form, and it no longer uses the effect.

May 14, 2007): If you like this post, you might also appreciate validation hints.

TrackBack

» Best of March 2007 from Minefeed.com
Every month we take a look around and select some of the most interesting web-development-related web-sites. [...] [Read More]

Comments (302)

Pimmm said:

That's a great article.
The end result is clean cut. I saw it on Vox already, but thanks for the "behind-the-scenes" look!

Charlie Park said:

An interesting tweak on forms. Thanks for writing it up.

Why, though, wouldn't you just use the :focus pseudo-class?

CSS Guy said:

@Charlie:

I can't envision how :focus would work here. The hint span is the element to show and hide, and there is no way in CSS for that to happen on the condition of another element's focus.

simu said:

nice article there.

I see one problem here, what if a user has js disabled but not css? then the hints will always be invisible for such a user since they are hidden over css...

to fix this problem I would assign all styles which are used by the js-hints, e.g. display, position etc., over javascript, if you do it like that, the hints are only hidden if js is activated and will degrade nicely otherwise.

or you could assign a class to the form over js if you prefer having the styles in the css-file.

Aaron Bassett said:

@CSS Guy:

It could be easily done using :focus and the adjacent sibling selector. Something along the lines of:

span { display: none; }
input:focus + span { display: inline; }

of course this will only work in browsers that understand the pseudo selector ':focus' and the adjacent sibling selector '+' (tested and works in FF2)

CSS Guy said:

@Aaron,

I see now - :focus and adjacent sibling selector combo. Nice for the modern set of browsers.

Somewhere out there on the wide wide world of web is a countdown clock that tells us when we can start ignoring IE6. Anybody know what it currently says?

Aaron Bassett said:

Knowing my luck it probably says:
Time remaining: NaN

And I could be wrong, infact I would love to be corrected on this...but I think IE7's support for selectors is pretty thin on the ground as well :(

Dave said:

Nice one! Beautiful interface in the front-end -- help when you need it most.

Gregg Bolinger said:

Very nice example. The only thing I'd do differently is give the SPAN tag and the INPUT/SELECT tags some common ID text and instead of looping through all the INPUT/SELECT elements on the page, just grab the one that matches up and display it:

<input
name="firstname"
id="firstname"
type="text"
onfocus="showHint(this.id);"
/>
<span class="hint" id="firstname_hint">Use your real name!</span>

document.getElementBy(element + "_hint").style.display = "inline";

That seems cleaner to me.

Chris said:

Why use definition lists (DL) for this? Hijacking markup that has a specific documented purpose for the convenience of your layout is a bad habit. The LABEL tag can be styled in place of DT and I'd rather see DIVs instead of DD.

I realize Vox set a bad example in that regard, but it might make sense not to propagate this sort of thing in a tutorial.

Thanks for the guide.

Adam Fortuna said:

Wow, great example. Think I'm going to mess around with this tonight, but as Chris mentioned, using spans for the hints.

Vincent van Scherpenseel said:

Also a great tweak would be to display the hints on mouseover :)

Paul Fraser said:

very cool, been looking for this sort of thing for a while now :)

PiratedTVPro said:

I like this alot. Thanks for the free Java! (can't stand those damned curly brackets)...

Chris said:

Good job! It looks very nice and the tutorial is easy to follow. I really like this site.

Matthew Davidson said:

I'm trying to find a way, like the VOX link, to keep the hint from hiding when I click on them. I want to be able to put hyperlinks in my hints. Any help?

web said:

For cleaner markup you could have used the alt="" attribute on the input for the copy and on focus use javascript to trigger that message in a window. That way you wouldn't have to make use of an unsemantic span.

Matthew Davidson said:

to get hyperlinks to work, a little reworking needs to be done. Gone is the onblur event.
add input field type="hidden" id="lasthint"

then change the prepareInputsForHints() function to be structured like this:


var inputs = document.getElementsByTagName("input");
for (var i=0; i<inputs.length; i++){
inputs[i].onfocus = function () {
document.getElementById("lasthint").value = this.id;
if(this.parentNode.getElementsByTagName("span")[0])this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
var newinputs = document.getElementsByTagName("input");
for (var j=0; j<newinputs.length; j++)
{
if (newinputs[j].parentNode.getElementsByTagName("span")[0] && newinputs[j].type != "hidden")
{
if(document.getElementById("lasthint").value != newinputs[j].id)
{
newinputs[j].parentNode.getElementsByTagName("span")[0].style.display = "none";
}
}
}
}
}

Dan said:

For what it's worth - with the version you created, the hints only work in the final two fields on Firefox 2.0.0.3 on Mac OS X 10.4.9. However, the Vox example works fine for all fields. Unfortunately I am too much of an ignoramus to tell you why this is.

Shakakai said:

To save five lines of javascript you could change prepareInputsForHints() to -->
var formElements = ["input", "select"];
for(var g=0; g<formElements.length; g++){
var inputs = document.getElementsByTagName(formElements[g]);
for (var i=0; i<inputs.length; i++){
inputs[i].onfocus = function () {
this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
}
inputs[i].onblur = function () {
this.parentNode.getElementsByTagName("span")[0].style.display = "none";
}
}
}

Hopefully I didn't miss a parentheses. Coding in this textarea is a little tricky.

Shakakai said:

It cut off a portion of my post. You can create an array of form elements to look for input and select respectively and loop over that rather than coding the same thing twice. DRY.

CSS Guy said:

Thanks for all the comments.

Let me see if I can respond to everyone.

@Gregg:
Nice approach with the onfocus="showHint(this.id);". I can see the appeal in that kind of organization.

@Chris regarding use of DL:
I disagree that using a DL to markup a form is wrong. I can't speak for why Vox chose to do so, but many times the needs of the client, visual appeal, and complexity of the form require markup in addition to form, fieldset, label, etc.. (In some cases, that even means using tables.) However, point taken about 'propogation'. So people reading this article: please note that just because this one form example is marked up with a DL, that doesn't mean you have to do it.

@PiratedTVPro:
Not Java. JavaScript.

@Matthew Davidson:
Good suggestion. I didn't consider that for this tutorial, but I appreciate you adding to it. I can see how that can be handy.

@web:
Yeah - that's another way to do it.

@Dan:
In my final example, the hints are purposefully only to show up for the last two fields. I think I stated that on that page. Let me know if I'm missing your point.

@Shakakai:
I'm no javascript guru, but I knew there would be a more efficient way. Thanks for sharing your code - I tried to modify your comment to match your intent. Remember to use "&gt;" for ">", even in the javascript code snippets.

Pensador said:

Thanks for the article; I will give it a try.

Rob said:

Why duplicate so much code? Couldn't you just create one array?

inputs = inputs.concat( document.getElementsByTagName("select") );

CSS Guy said:

@Rob:

I knew there must've been some way to be more efficient, but I didn't know how to concatenate arrays in JavaScript (I'm not the JS Guy). Thanks for sharing - I'll try it out.

Craig said:

One could use :focus and the adjacent sibling selector and although that doesn't work for IE, of course, it also it doesn't work for Safari, although it does work on everything else.

One still could use a Conditional Comment for IE to add the Javascript needed to make it work in IE but that would still leave Safari out in the cold.

Karen said:

CSS Guy: I think Dan means that the hints do not show up nicely in IE. They show up, but it is like the disappearing text trick thing in IE where if you scroll the text suddenly shows up, same with your boxes that the hints are in. (maybe just on our set ups?)

Ian said:

I agree with Chris. Using DT and DD is absolutely no different from using table based layouts. Both are not designed for the purpose of laying out forms.

If you're going to (as Chris put it) hijack HTML, you may as well use the better suited table.

The example is great BTW, I just don't deem it appropriate that you promote the use of illegitimate HTML

Web Design Glasgow said:

This actually highlights a problem I was considereing the other day - is there a way to get rid of that span for the pointer? I like to keep my markup semantic.

My first thought involved removing the left border from the box, and including the border in the pointer image, but this would give you an overlap on the top and bottom borders, and doesn't allow for boxes of varying height.

Any ideas?

Yeago said:

Cool idea. Gimmicky in most situations, though. =)

Panaboard said:

That is pretty slick. I now just have to re-arrange my page so that the "hints" are not over the top of anything...I would also like to play around to get them to match my site better so I have plenty to do...
----
Shredder

Leopold Porkstacker said:

WOW!!!! Great stuff!!!! Thanks for sharing the tip!!!

Fredrik Wärnsberg said:

Very nice article!
One thing that came to my mind when reading it is that it's unnecessary to add an extra div just for the pointer. Apply the pointer to the parent div instead (of course the image would need to be modified to fit this purpose; you'd have to add the border and some white yourself and make it about 400px high).

Rich said:

This is very cool.

What do you need to do in order to display different tips if there are two inputs on a single line?

kLAcK said:

This is a nice tutorial. I have implemented it fully, however I am having a problem when rendering in IE. It seems like IE does not draw the span correctly (borders are missing) the first time, but if the hint is shown and hidden again, it looks proper. Is there a way to force IE to redraw the screen? I also noticed that the Vox implementation does not have this problem, but their javascript is too cryptic for me!

Brent said:

Quote from Yeago:
"Gimmicky in most situations, though. =)"

Yeah, maybe it's gimmicky if you use it on obvious fields just for the sake of using it (like Vox).

But wonderful for offering hints w/o mucking up the initial view of the form with instructional text and in-line examples. It can mean the difference between making a form look simple vs. complicated and time consuming. Completed sign-up forms translates into dollars for most folks running an online business!

The "IA" Lives.

CSS Guy said:

@All:

Some folks have pointed out an IE6 bug, in which the border around the hint does not draw completely around the span on its first viewing, but then looks fine.

I'm baffled. I've tried height:1%, zoom:1, etc. to get around this, but so far, nothing.

If anybody can find a way out, please share. Until then, please use with caution. One would think I could have a decent code walkthrough that is bug-free.

Also, as for using forms with <dl>, <dt>, and <dd>, though I have not used them until this very post, I'm still not convinced they are bad ideas. One could argue that the <dt> to <dd< relationship is a valid one to apply to a form field label and the field it represents.

For example: "First name" could be a term (<dt>). The use is asked to provide the definition (<dd>) via an input field.

Tell me again why this is wrong? I think that's a valid argument that a definition list is well-suited to handle forms if the designer so chooses.

David Carriger said:

A co-worker pointed me to this site to ask me what I thought of this form feature. I thought it was cool...uh...until I observed that it had that IE6 bug. Hah! And about 90% of our site visitors are still using IE6. So...I began playing with the coding.

This is what I came up with...and (at least on my local computer and development center for my network) appears to work for IE6/7/FF2. And don't ask me why, but by leaving out - what should and WOULD be considered proper - attributes for the classes used, things snapped to...AND...even MORE peculiar, I was forced (in my fix) to HAVE to place the "background-color" property directly in the "hint" SPAN...go figure.

In any case...it seems to work. Awesome job of coding CSS Guy!

CODING::: (core elements, only)

<style type="text/css">
/* The hint to Hide and Show */
.hint {
position: absolute;
display: none;
right: -250px;
width: 200px;
margin-top: -4px;
border: 1px solid #c93;
padding: 10px 12px;
color:#000000;
background-color: #ffc;
background: url(http://images.automart.com/imgs/design/ag/agonyx/autoblue/focused-left.gif);
background-position:-10px 5px;
background-repeat:no-repeat;
}

/* The pointer image is hadded by using another span */
.hint-pointer {
position: absolute;
left: -10px;
top: 5px;
width: 10px;
height: 19px;
background-color: #f2fcf1;
background: url(pointer.gif);
}
</style>

<script type="text/javascript">/* Not included in this submittal; however, no changes from original scripting. */</script>

<dl>
<dt>
<label for="firstname">First Name:</label>
</dt>
<dd>
<input
name="firstname"
id="firstname"
type="text" />
<span class="hint" style="background-color: #ffc;">This is the name your mama called you when you were little.<span class="hint-pointer"> </span></span>
</dd>
<dt class="button"> </dt>
<dd class="button">
<input
type="submit"
class="button"
value="Submit" />
</dd>
</dl>

...hope this was helpful.

CSS Guy said:

@David,

I think you've hit on something! It turns out that including a background image as part of the .hint was all that was needed to get this working in IE6!

So if we go to .hint and change this:

background-color: #ffc;

to this:

background: #ffc url(pointer.gif) no-repeat -10px 5px;

it works!.

(Note that the background image is positioned so that it won't really show up. It's the same image as what would be in .hint-pointer span, so no overhead.)

David, I think you were having to explicitly state the background-color within the tag because, in the CSS, where you declare "background:", you didn't declare the color there. Since you were only declaring the background-image in that one statement, you would've probably gotten away with using "background-image" instead of just "background". When you use "background:", the color is expected, too.

Thanks for playing with this, David. I think we've got ourselves a fix. I'll need to update the article to reflect that.

David Carriger said:

Hey...was glad to help. Especially given that I have hopes of using this cool utility on my companies 2 sites. If you have no objections, that is. :-)

I'll let you know if & when my Product Development team approves my desired use for this tool, so's you can take a look-see.

Thanks for cleaning up my foo-pah coding. :-))

Best Regards, David

CSS Guy said:

@David,

As far as I'm concerned, have at it - it's not my effect to give anyway. I just wanted to show how to achieve it.

gianluca said:

Well done!!!

A question: how i can use a hint window in a textarea?

Thank you!

CSS Guy said:

@gianluca:

See example 7 for a form with a textarea.

Jason Coleman said:

Nice writeup. I wonder if the Vox folks are wondering why so many folks are getting to their registration page and failing to sign up. They'll probably change their form or something ("I told you those javascript thingies were going to break folks' browsers!"). ;)

David Davis said:


A coworker (that did the css on the regform) gave me the link to this post. I did the js on vox, btw. ;) Good writeup on the technique!

Cheers
David

wotaewer said:

great stuff.

really appreciated your understandable writing, and even though I didn't have a lot of knowledge about javascript, i got it ;)

Martin said:

Hi

I'm trying the last example which should have the IE6 fix, but still, using IE6, it does not mark up the whole border first time focusing on an input field.
http://www.askthecssguy.com/examples/formfieldhints/example06.html

Anyone who can confirm this?

CSS Guy said:

@Martin:

I'm trying to get it again on two machines running windows with IE6, but it's looking ok here. What happens when you view example07.html?

Steve Sockey said:

How do I add 2 form field together. If I cheage the following from * to + I dont get the total but a combination of the 2 numbers
such as 2 + 3 = 23

var Total = Units * Rate


<html>
<script javascript>
<!-- Begin
//
// Server Side Code Would Be Required Above Script To Set Text Field Values From Database on OnLoad()
//

function DoMath(){
var Units = document.frmData.Units.value
var Rate = document.frmData.Rate.value
var Total = Units * Rate
document.frmData.Total.value = Total
}
<!-- End
</script>
<body onload="DoMath()">
<form name="frmData" method="POST" >
Units:<br>
<input type="text" onchange="DoMath()" name="Units" size="20"></p>
<p>Rate:<br>
<input type="text" onchange="DoMath()" name="Rate" size="20"></p>
<p>Total:<br>
<input type="text" name="Total" size="20"><br>
<input type="button" onclick="DoMath()" value="Update" name="B1"><input type="reset" value="Reset" name="B2"></p>
</form>
</body>
</html>

CSS Guy said:

@Steve:

Dunno. Try the sitepoint javascript forums.

Helmar said:

@Steve:
you are trying to add strings, not numeric values. Take this code instead:

var Units = eval(window.document.frmData.Units.value);
var Rate = eval(window.document.frmData.Rate.value);

Mark Snape said:

A nice understandable writeup!
Is there anywhere that the addloadevent code is explained. I know little JS and tend to come unstuck when trying to combine different techniques from different sources in one page.

I also would like to place links in the hint so thanks also to Matthew Davidson.

stefan said:

thanks for the interesting article.

what's wrong with using title-attributes on each input? they are accessible, don't need JS or CSS, and they work on mouseover.

too easy?

CSS Guy said:

@Mark Snape:

Good point. "addLoadEvent" was written by Simon Willison, who can probably explain it better than I can. I learned about it when I read Jeremy Keith's "DOM Scripting", and have used it regularly since then to attach several scripts to the window.onload event.

@stefan:

The title attribute is always a good idea, and it has served as an easy way to get the tooltip effect. Howeveer, it doesn't quite achieve the same effect as the javascript-powered hints discussed here. (For one, they don't work when tabbing through the fields.) I encourage use of the title attribute anyway, so I'm with you, there.

Richard@Home said:

Excellent tutorial, and some great feeback in the comments.

To stefan: I'd be tempted to use the title tag too, but in our experiments @ work, the title tag only allows a maximum of 255 characters in some browsers. Also, adding extra markup to the title tag (such as strong tags, paragraphs etc.) behaves oddly in older browers.

As to the popup technique as presented here, I'd be tempted not to use display: none; in the stylesheet so the tips appear by default when javascript isn't available. You could augment the script to add display: none; when it runs.

nonplus said:

Very nice approach, but having to embed the <span class="hint-pointer"> </span> with each hint is not very designer-friendly. However, there is no reason why the JS that hooks up the events shouldn't at the same time inject the pointer span.

If you use the following as a replacement for your prepareInputsForHints() function, the hint-pointer spans will be added automagically. And the code will check for hints for input, select and textarea controls.

function prepareInputsForHints() {
    var tags = ['input', 'select', 'textarea' ];
    for(var t = 0; t < tags.length; t++) {
        var inputs = document.getElementsByTagName(tags[t]);
        for (var i=0; i<inputs.length; i++){
            connectInputHint(inputs[i]);
        }
    }
}
 
function connectInputHint(input) {
    var span = input.parentNode.getElementsByTagName("span")[0];
    if(span) {
        // Add pointer
        var pointer = document.createElement('span');
        pointer.className = 'hint-pointer';
        pointer.innerHTML = ' ';
        span.appendChild(pointer);
 
        // Hook up events
        input.onfocus = function () {
            span.style.display = "inline";
        }
        input.onblur = function () {
            span.style.display = "none";
        }
    }
}

bugmap said:

Good article :-)

The example (vox) seems to have removed the "Hints" :-) check it!

jigga said:

I love this example and I'm gonna use it but I still have the problem of getting it to work in IE6. If someone finds another soulution please post it here..Thanks..

CSS Guy said:

@jigga,

Can you post a link to your form?

Motorcycle Guy said:

This is pretty cool, it'll be nice when ie 6 and other browsers that might not support this are no longer a sizable %.

Jason Coleman said:

I had to remove the "display: none;" from the CSS definition for .hint-pointer {} to get this to work. Might be a typo in your article.

Great script though.

Tom said:

Very useful! Thanks!

RaJ said:

Its very cool. Keep posting more.

Shaun said:

Very useful, thanks for the information. Love the site, very informative

Mike B said:

First off, excellent article!
I'm running IE6 and still seem to have a display issue with the examples. The first on-blur event is displayed with some or no boarders, the next time its ok.

I did a little playing and it seams when i commented out the "position: absolute" from the css class ".hint-pointer", it solved the boarder display issue. Of course by doing this you lose the ability to position the pointer!

I did a bit of playing with the script and come up with this as a work-around:
I replaced the pointer span with a div and moved it to the beginning of the hint span.
I edited the ".hint" style so there was padding on all sides except the left.
Then used "position: relative;" in the ".hint-pointer" style to move the pointer.

Some people are probably going to curse at me for the way i have set this up, but hey......it works for me.

Can anyone confirm that they are having trouble with the original version but my work around is working for them?

A temporary example

corkey said:

for accessibility (well screen readers) should you not have the form hint before the input field?

this link has a nice example maybe someone can have a play and incorporate???

http://simplyaccessible.org/assets/formexample-errormessages.html

corkey said:

for accessibility (well screen readers) should you not have the form hint before the input field?

this link has a nice example maybe someone can have a play and incorporate???

http://simplyaccessible.org/assets/formexample-errormessages.html

guilty said:

thanks you

Cj B said:

Hello! Great example! I've found it very useful. However. I was wondering if there was a way to make it show the hints when someone hovers their mouse over a table row?

Thanks!

Cj B said:

Hi There! I was able to get this to work on mouseover with table rows using the following code:

  var tableRow = document.getElementsByTagName("tr");
  for (var m=0; < tableRow.length; m++){
    if (tableRow[m].getElementsByTagName("span")[0]) {
      tableRow[m].onmouseover = function () {
        this.getElementsByTagName("span")[0].style.display = "inline";
      }
      tableRow[m].onmouseout = function () {
        this.getElementsByTagName("span")[0].style.display = "none";
      }
    }
  }  

You then just add the span with the hint in the LAST column of each row you want to have a hint in. You'll also have to make some minor changes to the CSS.

You''ll also note that I added an "if" statement. I would suggest adding this to all the other for loops as this will eliminate all the javascript errors that can occur if every row doesn't have a span tag.

For our implementation we also wanted to be able to dynamically turn the context help on or off. To do this I created a toggle function which depending on the current value of a cookie, toggled the code so that it set the EVENTs back to null.

Thanks for this great tutorial!

Cj B said:

Hi There! I was able to get this to work on mouseover with table rows using the following code:

  var tableRow = document.getElementsByTagName("tr");
  for (var m=0; < tableRow.length; m++){
    if (tableRow[m].getElementsByTagName("span")[0]) {
      tableRow[m].onmouseover = function () {
        this.getElementsByTagName("span")[0].style.display = "inline";
      }
      tableRow[m].onmouseout = function () {
        this.getElementsByTagName("span")[0].style.display = "none";
      }
    }
  }  

You then just add the span with the hint in the LAST column of each row you want to have a hint in. You'll also have to make some minor changes to the CSS.

You''ll also note that I added an "if" statement. I would suggest adding this to all the other for loops as this will eliminate all the javascript errors that can occur if every row doesn't have a span tag.

For our implementation we also wanted to be able to dynamically turn the context help on or off. To do this I created a toggle function which depending on the current value of a cookie, toggled the code so that it set the EVENTs back to null.

Thanks for this great tutorial!

CSS Guy said:

@Cj B:

Nice stuff. Thanks for sharing how you customized the technique.

David said:

Too many comments to read through, but the article still has an error so I guess it hasn't been brought up. In the .hint .hint-pointer rule, you have display:none in there, but it shouldn't be. :)

CSS Guy said:

@David:

Yikes! It's fixed. Thanks.

ceviri said:

Good job! It looks very nice and the tutorial is easy to follow. I really like this site.

kapi said:

good text. thank yoouuu

kale kapi said:

thanks good text

Jay said:

Excellent article... now how can we kill IE6? It should have been dead a long time ago - but yet there it is causing us all kinds of headaches!

Sven said:

Hello CSSGuy,
thanks for the tip on the tooltip. ;)
I tried it and it works fine but W3c validation failed on javascript:
line 70 column 30 - Erreur: character ";" not allowed in attribute specification list
line 70 column 30 - Erreur: element "inputs.length" undefined
line 85 column 31 - Erreur: character ";" not allowed in attribute specification list
line 85 column 31 - Erreur: element "selects.length" undefined
line 97 column 8 - Erreur: end tag for "selects.length" omitted, but OMITTAG NO was specified
line 85 column 16 - Info: start tag was here
line 97 column 8 - Erreur: end tag for "inputs.length" omitted, but OMITTAG NO was specified
line 70 column 16 - Info: start tag was here

How can it be fixed (if it can)?

kale buzzbar said:

thanks good text

CSS Guy said:

Sven:

Though I'm getting errors on validation, they aren't the ones you mentioned. Here's the service I used.

What's the url of the page you are validating?

Amit said:

HI,
I am currently using a single .css file for styling my webpage. I have 4 more .css files with different design. Now I want to add an option which would give the user an option to chose which stylesheet he/she prefers for my webpage and save that information in a cookie so that on the next visit that particular stylesheet is loaded.

I tried using JS but the variables dont get loaded. Help would be appreciated.

Thanks n Regards
Amit

kale kapı said:

I tried using JS but the variables dont get loaded. Help would be appreciated.

Shamma said:

If i used the form fields hints in the template concept the script function doesn't work,, so plz depict how to implement form field concept in template

jvisinand said:

For the one who use jQuery javascript library, the javascript code could be replaced by:

$(document).ready(function() {
$(":input").focus(function() {
$(this).parent().find("span:first").css('display','inline');
})
$(":input").blur(function() {
$(this).parent().find("span:first").css('display','none');
})
});

Mark said:

Great post, but I think I've encountered a little bug in Safari whereby the hints won't appear when used with radio buttons. They work fine with other input fields. Safari 2.0.4 I'm using.

download said:

$(document).ready(function() {
$(":input").focus(function() {
$(this).parent().find("span:first").css('display','inline');
})
$(":input").blur(function() {
$(this).parent().find("span:first").css('display','none');
})
});
?

Zauberer Zauberkünstler Zaubershow said:

Hi, nice web - site, and thanks a lot for all the useful informations, kind greetings from germany

dekorasyon said:

What's the url of the page you are validating?

kale kapı said:

They work fine with other input fields. Safari 2.0.4 I'm using.

youtube said:

thank you for his info

Amerikan kapı said:

Hi, nice web - site, and thanks a lot for all the useful informations, kind greetings from germany

JimThePCGuy said:

I was wondering how much you charge for a custom form like the ones posted? If you go to my website you'll see the form I'm currently using. It's good, but it could be a LOT better (:o). Right now, I use "required" in three of the fields, but the forth is hidden until the drop-down is selected. So basically I have no idea how to use either a tip like you show, or a "required" field. I am WAY out of my element with most things programming.
"http://www.jimthepcguy.net/form.html" This is the page with the form. Any help would be appreciated! Thanks in advance...By the way, if you could email me I would greatly appreciate that also!
Kind Regards,
JimThePCGuy

Oliver Martin said:

Hi CSS Guy,

I have everything working BUT there is no space below the form. Why wouldn't my website show a space below the form like the rest of the elements on my website?

An image of my problem

Daniel X. said:

Hi.

Great technique!

Despite the fix for IE6, my browser still showed the weird behaviour. It was fixed once I used the property visibility (switching between 'hidden' and 'visible'). No more 'draws incorrectly on first show' errors here ...

Regards,
Daniel

CSS Guy said:

@Daniel:

Thanks for posting about using the visibility property.

TMaxim said:

I tried using JS but the variables dont get loaded. Help would be appreciated.

Andrew said:

Great article. I've been using this technique in a new form I'm creating. I've run into a problem and am hoping you may be able to shed some light on it. I've got a scrolling checklist (as per http://www.c82.net/samples/checklist-samples.html ) with an associate hint, it works in Firefox, but not IE6/7.

Here is my markup:
  <fieldset>
     <legend>Legend here</legend>
     <ul class="checklist">
        <li><label><input name="opt1" type="checkbox" /> Option1</label></li>
        <li><label><input name="opt2" type="checkbox" /> Option2</label></li>
        <li><label><input name="opt3" type="checkbox" /> Option3</label></li>
     </ul>
     <span class="hint">Hint here</span>
  </fieldset>

and here's my javascript:

var uls = document.getElementsByTagName("ul");
for (var k=0; k<uls.length; k++){
   if (uls[k].parentNode.getElementsByTagName("span")[0]) {
      uls[k].onfocus = function () {
         this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
      }
      uls[k].onblur = function () {
         this.parentNode.getElementsByTagName("span")[0].style.display = "none";
      }
   }
}

I would expect the hint to display when the <ul> has focus, which it does in FF, but not IE....

Any ideas?

Thanks!

chain saw said:

I was wondering if you or anyone that reads you site could help me with something. I have been trying to input this code into my site for a while now but to no avail:

a img {
border:0;
}
img. figure {
max-width:460px;
border:2px solid #f7f7f7;
}
img. figure-a {
margin-left:auto;
margin-right:auto;
display: block; }
img. figure-b {
float: right;
border:0;
margin:0 0 6px 6px;
}

Could I have some4hting wrong with something in the code that is causing me to have a problem? I have gone over it a few times and still have yet to find what could be causing me the problems that I have been having. I would really like anyone that could help me on this to get in touch with me please. I have a few other issues that I have been having that I would really like for someone to help me on.

Markus said:

Hi!

I rewrite your hints using Prototype.js and LowPro.js behaviors. This is the result:

HTML Example:

<p>
<input type="text" id="username" name="username"/>
<span class="hint" style="display:none"> Only a-z characters allowed</span>
</p>

I have had to put an ugly style="display:none" due to a javascript issue when it is declared by css.

Javascript:


var Hint = Behavior.create();
Object.extend(Hint.prototype,{
initialize: function(){
if(this.hint = this.element.up().getElementsBySelector('.hint')[0]){
this.bindDomEvents();
}
},
bindDomEvents: function(){
Event.observe(this.element,'focus',this.hint.show.bind(this.hint));
Event.observe(this.element,'blur',this.hint.hide.bind(this.hint));
}
});
Event.addBehavior({"input[type='text'], select, textarea": Hint()}); // Example using tags as selector
Event.addBehavior({".hasHint": Hint()); // Example using a class as selector

In Event.addBehavior you can put whatever you want using css selector sintax.

It's shorter than yours, but requires Prototype, a slightly heavy library if you only use it for this purpose.

Cheers!

Skischule said:

thanks you Css Guy for all the tips and codes.
good work.

digital portrait artist said:

Hello css guy! I’ve included your codes and tips in my class today. If I did it my way, the students wouldn’t have finished their activity in time. Thanks and more power.

TMaxim said:

I have included your codes on the site, and at me that it has not turned out. You could not help me?

Meble said:

OK, good article..

BaltikS said:

A coworker (that did the css on the regform) gave me the link to this post. I did the js on vox, btw. ;) Good writeup on the technique!

Freese said:

Well I´ve been trying to use this technique in a new project and actually almost everything does work. Only, as expected, in IE6 I still haven't figured out a way to solve 2 bugs. The border bug is still there, alltough I placed a background image in the .hint element.
The little arrow graphic does appear perfect in Firefox but in IE6 I only get a weird gray border. Take a look at the problem (with IE6) here:

http://news.ztc-solutions.de/

Thank you for any kind of help you could provide me.

Freese said:

Thank you for your answers CSSGuy, I haven´t been able to fix the bugs, but I think I´ll have to live with them.

Another issue I that I´m having at:

http://news.ztc-solutions.de/

is that when I cklick the send button, the hint of the first Element appears, altough the send button, doesn´t have any Element. I have compared you examples with mine, but I cannot find any differences. IE drives me sometimes crazy...
Thank you!

CSS Guy said:

@Freese,

The script is attaching the event to every input on the page, including the submit button, which is also an input element.

Perhaps the best thing to do is to only attach the event to text inputs, excluding submit inputs.

mirc said:

thanks best regards.

insaat said:

insaat ihale fuar dekorasyon yapı malzemeleri insaat sektörü insaat malzemeleri konut

granit said:

granit mermer cimstone mutfak tezgahı

dekorasyon said:

insaat ihale fuar dekorasyon yapı malzemeleri insaat sektörü insaat malzemeleri konut

robert said:

Perfecto!! == PERFECT!!

sharp aquos said:

Hi, nice web - site, and thanks a lot for all the useful informations, kind greetings from germany

mirc said:

thanks very good super

sex said:

thank you

mark said:

Very useful for my next project. Thanks.

PraP said:

Nice One.

Car Audio said:

This code is great..

Thomas said:

wow, really nice post! i'll use it in one of my projects. thx. :)

www.r10.net küresel ısınmaya hayır seo yarışması said:

good text. thank you :)

www.r10.net küresel ısınmaya hayır seo yarışması said:

wow, really nice post! i'll use it in one of my projects. thx. :)

sex shop said:

This code is great..

sohbet odaları said:

thanks very good

Ensest Hikayeler said:

thank you admin. super olmus ellerine saglik

Ensest Hikayeler said:

thank you admin. super olmus ellerine saglik

Antyki Starocie said:

Nice article, and great infos!
I like the design of this site!!!
Regards

Futbol izle said:

It helped me alot thanks for the great article, best regards

Ebim said:

I will use them in my website thanks for the help.. great article

John Dekker said:

Nice article

thanks!

Rakesh said:

Nice article.But i have a severe problem.
I've used this form for client website.Its been working nice..but the problem now is the client has asked me to put a body onload function so that when the page is loaded top most input box will be focussed and hence the
tooltip will be displayed.
so i've added the following code to my body tag

<body OnLoad="document.business_listings2.company_name.focus();">

But it seems to be not working now..Please Help me !!
I've tried it out in the example file also..still its not working.What could be the problem.

Thanks in advance

CSS Guy said:

@Rakesh,

Rakesh,

You'd want to make use of the addLoadEvent function.

In your javascript file, add these lines:

function putFocusOnField() {
document.business_listings2.company_name.focus();
}
addLoadEvent(putFocusOnField);

Then remove the onload attribute from your html completely.

Tony King said:

Great article. I am implementing this technique on some of my forms!


~P.S. - The snow here is yellow, not white. We have a lot of animals.

Maydin said:

Despite the fix for IE6, my browser still showed the weird behaviour. It was fixed once I used the property visibility (switching between 'hidden' and 'visible'). No more 'draws incorrectly on first show' errors

akademi türkiye said:

Despite the fix for IE6, my browser still showed the weird behaviour

çanta said:

Great article. I am implementing this technique on some of my forms...

Kale said:

Great article. Thanks. But css is very difficult for me. Because ı ama new:)

Damjan Mozetič said:

Thanks for the well written article. I was just searching for something like this.

nullamatix said:

Wow, what a great bit of information. I'll definitely implement this nifty little trick on some of my client's sites, they'll love it.

Thanks!! Great blog - *subscribed*

Tom M said:

Great, this fixes a problem I was having with my form. I have have been looking for a simple fix. Great article!

Frank said:

Great Script. I like the usability

RapidshareFilms.com said:

Ohh damn...i never knew all this stuff :)

Thanks bro!

Greetings from http://RapidshareFilms.com

Online Shopping Mall said:

I disagree that using a DL to markup a form is wrong. I can't speak for why Vox chose to do so, but many times the needs of the client, visual appeal, and complexity of the form require markup in addition to form, fieldset, label, etc.. (In some cases, that even means using tables.) However, point taken about 'propogation'. So people reading this article: please note that just because this one form example is marked up with a DL, that doesn't mean you have to do it.

Jolene Blalock said:

Great article on CSS! Thanks for the info.

ses kayıt said:

This actually highlights a problem I was considereing the other day - is there a way to get rid of that span for the pointer? I like to keep my markup semantic.

website submission service said:

it is nice to have..I kind of prefer 100% CSS but this instance, javascript can be given a break.

Efe Properties said:

This is a great search suggestion

The Party Pills said:

This is a very good search suggestion
Thank you

Filestock.NET Best File Hosting said:

That is pretty slick. I now just have to re-arrange my page so that the "hints" are not over the top of anything...I would also like to play around to get them to match my site better so I have plenty to do...
----
http://www.illegalworld.org
http://download.filestock.net

Filestock.NET Best File Hosting said:

it is nice to have..I kind of prefer 100% CSS but this instance, javascript can be given a break.

linkfeads said:

Wow i found this to be very informative and it's given me a few idea's for my own projects, thanks!.

Wynajem Autokarów said:

Thanks for the article and your efforts. I know nothing of Javascript and I am pleased and excited to use this code on a page I am working on.

ajax said:

thanks for the hints

bülent said:

this is great article,thanks for sharing

acne treatment said:

This is wonderful information. You helped me out. Thanks.

Marcis Gasuns said:

Is there any way to get the bullet on the left side as in the vox preview image?

vbulletin said:

Best comment for writing for css thanks best regards

Silberringe said:

i find the american blogs more interessting then german blogs. and there is more quality in the blogs.

compliment and so on.

best regards

c.

Pates said:

I'm still having a tough time with javascript and CSS but this has helped a lot. Thank you.

Fape said:

Thanks a lot! you really help me out! This information is very valuable.

ilahiler said:

it is nice to have..I kind of prefer 100% CSS but this instance, javascript can be given a break.

evkurun said:

good post!

logan said:

thanks.

Shxtrading said:

tricky

ctraos said:

exelente postt muchas gracias

Underwater sea plants said:

I had some Problems with the CSS but this one seems to help out!

great sharing!!

müzik dinle said:

I think its very very useful information.. thank you for all that..

rap said:

thanks!!!!

mynet said:

That's a great article.
The end result is clean cut. I saw it on Vox already, but thanks for the "behind-the-scenes" look

güzel sözler said:

thanks very much

K said:

This site has the best use of this ever. It gives hints and validates the felds at the same time.
http://members.freewebs.com/Signup/signup2Z.jsp

şarkı sözleri said:

thanks bro it helped me much.

Lastminute Sebastian said:

This is nice to have. However, that's great! thanks for post...

şiirler said:

duz anybody know what position: absolute; does?
mail me add ian12@gmail.com please. thanks for the post too.

SEO Techniques said:

NIce explaination about css code, i go through many article regarding to css but here i found something new for my knowledge.

Maxim said:

Good lesson, I will use it on my new website. Thanks

Jeremy said:

Great script! Is this copyrighted in any way? I would like to use it. Please let me know at the email address given. Thanks!

MMORPG said:

good css article :D Thx. This'll help

indir said:

useful thx.

türkçe rap said:

well thats useful for myself. thanks for the nice post.

Chad Edge said:

Got a question:
I'm using this script for validation alerts on invalid fields (eg: when a domain name isn't valid, a red exclamation icon appears; hovering the image reveals the tooltip span). Once the field is corrected, I delete the span and reload prepareInputsForHints();
Unfortunatly, hovering the (now a green checkmark) image still tries to fire the tooltip reveal (on a span that no longer exists).
Any thoughts?
It looks like the check for if(inputs[i].parentNode...) still proves true, even though there's no span inside the current DD.

CSS Guy said:

@Chad Edge:

Got a link where I can check it ou?

dizi izle said:

thanks

Bayswater said:

Just wanted to show you another nice version of this:
https://www.fullrate.dk/bestilling/

(mouseover fields)

Alessandra Ambrosio said:

Good post :D Thx for information

Mila Kunis said:

Great article, cant remember the last time i learned anything useful like that in a while.

David said:

Great script, how could I clear the default value inside the input field? This coding overwrotes the usual way I would do it.

Marcel Casado said:

Hi,

I like the hint script a lot but I'm having a rendering problem with IE6 and IE7. I got a form in a table with rows with even and odd background color. When the hint pops up some of it hides under the background color row. I'm using this in the context of the Liferay portal and the hint gets hidden by another portlet also. I'm pretty sure it's not a z-index problem.
I've been googling around ie bugs but I can not figure out what is wrong. Sorry I don't have an URL to show the problem. But I can email an screen shot.
Any help would be greatly appreciated. If I can not fixed I would have to find another way to display hint on my forms

Thanks in advance,

-Marcel

bahçelievler said:

Nice stuff. Thanks for sharing how you customized the technique.

alışveriş said:

Cool idea. Gimmicky in most situations, though.

Mario said:

Thanks for the tips man! Great help.

Matthew said:

Hi there,

Anyone has any idea how to get this working with ASP.net textbox, ect?

Tłumaczenia symultaniczne said:

Really good article,I'll use this information in my work

SEO Service said:

Thanks for shar with us, its a really nice article.

Albetien said:

Please help!!! I dont know a lot about HTML or javscript or anything but I am starting my own business and need a website. I have already done a lot without help but I have no idea how to create a form box that my customers can enter their names,numbers,addresses, and ect. into so that they can create logins and buy items. PLEASE HELP

email me at lolrsq18@aol.com

Albetien said:

And FYI I dont have money to buy anything helpful

Lauren said:

I got this script to work great by itself. But when I try adding code for default text that appears as an example but disappears when the user edits. This is the code I'm using. It works by itself, but not on fields that use hints.

http://www.bradino.com/javascript/clear-textfield-default-value-onclick/

rainmcr said:

I love your blog cssguy, great tools, invaluable website. I'm having an issue, the tips only seem to work for me if they are in the dl, dt, dd tags; when I remove those they no longer work, additionally, the styles seem only to work if i have them on the page rather than in my css file. I was however able to move the JS to my included JS file. Any suggestions?

CSS Guy said:

@rainmcer:

You may need to share a link for me to see what's happening. There's no reason it shouldn't work with styles in an external sheet (as long as image paths are the same).

World said:

I have been looking for this information for days. Thanks a lot.

leo said:

thanks

newss said:

very cool, been looking for this sort of thing for a while now :)

Andy said:

A simplified version is the registration form for green24.net.

It basicly loopes through all input fields and add a function on those fields.
This functions looks for the nextSibling and set the display accordingly.

There is no need for dt, dd etc.

tt

G Web said:

This really makes sense, going to be trying it out shortly, thanks, Goran.

shai said:

Hi thanks for this.

I am using this but when i use a texfield the hint wont show up.
Can you tell me why?

Thanks.
Shai

shai said:

Hi Thanks for this one.

Can you tell me why the hint doesn't show up when i use a textfield?

Thanks.
Shai

Jorge Alvarez said:

Hi:

If you are using prototype there is a better and simpler way to load the function:

Event.observe(window, 'load', function() {
var inputs = document.getElementsByTagName("input");
for (var i=0; i // test to see if the hint span exists first
if (inputs[i].parentNode.getElementsByTagName("span")[0]) {
// the span exists! on focus, show the hint
inputs[i].onfocus = function () {
this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
}
// when the cursor moves away from the field, hide the hint
inputs[i].onblur = function () {
this.parentNode.getElementsByTagName("span")[0].style.display = "none";
}
}
}
// repeat the same tests as above for selects
var selects = document.getElementsByTagName("select");
for (var k=0; k if (selects[k].parentNode.getElementsByTagName("span")[0]) {
selects[k].onfocus = function () {
this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
}
selects[k].onblur = function () {
this.parentNode.getElementsByTagName("span")[0].style.display = "none";
}
}
}
});


Anyway thank you for the post.

Regards,

Jorge

Alex @ Webson Design said:

Very nice, thanks for sharing... I like that you kept it short, I really hate it when I search a small script, as example for a ajax popup for a small form and I find only solutions that need to include in the header 200-300 Kbs of javascript files, only for a simple popup...

david said:

Hello, many thanks for this USEFULL script because i will use it for user registering when my new version will be launch. Regards, David

türkü dinle said:

wow! thanks man. it is one of the good results that I could find on the net! bookmarked! n waiting for announcements.
cheers robert.

Gift Blog said:

WOW!!!! Great stuff!!!! Thanks for sharing the tip!!!

KPSS said:

good work my friend.thank you

Mark said:

Thanks Maydin,
That solved the problem with IE7 too. Switching the "display:none;" to "visibility:hidden" in the css, then making the corresponding change in the .js file fixed the problem with the partial border display! Good job!

mirc said:

That solved the problem with IE7 too. Switching the "display:none;" to "visibility:hidden" in the css, then making the corresponding change in the

mirc indir said:

I'm having an issue, the tips only seem to work for me if they are in the dl, dt, dd tags; when I remove those they no longer work, additionally, the styles seem only to work if i have them on the page rather than in my css file. I was however able to move the JS to my included JS file. Any suggestions?

film indir said:

the styles seem only to work if i have them on the page rather than in my css file. I was however able to move the JS to my included JS file. Any suggestions?

divx film indir said:

Hello, many thanks for this USEFULL script because i will use it for user registering when my new version will be launch. Regards, David

sohbet said:

I like that you kept it short, I really hate it when I search a small script, as example for a ajax popup for a small form and I find only solutions that need to include in the header 200-300 Kbs of javascript files, only for a simple popup...

chat said:

need to include in the header 200-300 Kbs of javascript files, only for a simple popup...

Tomas Tvorba said:

Nice work guys. It could be like object, it would be even better. Thanks for your work.

travesti said:

great works thanks for sharing

Merry Christmas to all

Opinie o liceach said:

Is there anywhere that the addloadevent code is explained ?

Serwis drukarek HP said:

This is overly model dependent - according to some models Uranus and Neptune are aborted cores of gas giants like Jupiter and Saturn.

CSS Guy said:

@Opinie

addLoadEvent is explained here:
http://simonwillison.net/2004/May/26/addLoadEvent/

Pozycjonowanie stron internetowych said:

The only thing I'd do differently is give the SPAN tag and the INPUT/SELECT tags some common ID text.

Fitness said:

thx for the great stuff

ilahi dinle said:

it is very good

ilahiler dinle said:

it is realy super

oyunlar said:

addLoadEvent is explained here:

mirc said:

Human? What is the last letter of the alphabet? (required

Red Royal said:

good shared.. thanks..

MissANN said:

WOW!! thank you so much for this!! you're so awesome!!! ^____^

bed and breakfast said:

Great site

bed and breakfast said:

Great site

stuart said:

Is there a way that you can double click on an input field and make Java paste whatever is in the paste buffer into the field?

We have an app that would greatly appreciate the ability to double click a non-editable field to copy the contents, and then move to an input field and double click it to paste the contents into the field.

Can this be done in java script (or any other browser app?

I know I can ^C and ^V to cut and paste the value but it's slower and most users won't use the shortcuts. Most use the edit cut and paste options which takes way longer.

Thanks!
Stu

CSS Guy said:

@Stuart:

My concerns aside, if there was a way to do it, I don't know it.

toki said:

an this be done in java script (or any other browser app?

ESharpe said:

Nifty little script; I like it and will use it. Issue I found was that you can't use any other spans attached to inputs or selects or formhints will try and take them over as well. So I've specified the class it should look for and voila ... issue gone! Hope this helps someone facing a similar problem.

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

function prepareInputsForHints() {
var inputs = document.getElementsByTagName("input");
for (var i=0; i

// test to see if the hint span exists first
if (inputs[i].parentNode.getElementsByTagName("span")[0]
&& inputs[i].parentNode.getElementsByTagName("span")[0].className
&& inputs[i].parentNode.getElementsByTagName("span")[0].className == 'hint'
) {
// the span exists! on focus, show the hint
inputs[i].onfocus = function () {
this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
}
// when the cursor moves away from the field, hide the hint
inputs[i].onblur = function () {
this.parentNode.getElementsByTagName("span")[0].style.display = "none";
}
}
}
// repeat the same tests as above for selects
var selects = document.getElementsByTagName("select");
for (var k=0; k if (selects[k].parentNode.getElementsByTagName("span")[0]
&& selects[k].parentNode.getElementsByTagName("span")[0].className
&& selects[k].parentNode.getElementsByTagName("span")[0].className == 'hint'
) {
selects[k].onfocus = function () {
this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
}
selects[k].onblur = function () {
this.parentNode.getElementsByTagName("span")[0].style.display = "none";
}
}
}
}
addLoadEvent(prepareInputsForHints);

theme download said:

@ESharpe thanks.and thank for article.

Shyju said:

This is really a cool script,When i tried to use this with a HTML Table, the hint Span's are not displaying adjacently to my input text box. IT is displaying at the right most side of the screen .Can any one tell me how to solve this ? Thanks in advance

ESharpe said:

One thing I would like for this script to do is some math :) Okay, what I mean is currently the hint is designed to show 250px right of the input field but what I would like is for it to always show 5 pixels away from the right edge of the input field.

I have quite a few forms on my site and some of them are in the center column in a 3 column page and the hints are actually displaying in the 3rd column (right column) and what's worse I can't see abl to get z-index to work so the hint is below the content in the right column.

If your form is compact and input fields close together then hints will also get hidden under the input field in the column below.

Great script but it needs a little more under the hood.

Till said:

Fabulous! I first saw this kind of technique use in the MySpace registration form. Thanks for sharing with us.

The registration form of MySpace looks very similar to your screenshot. So anybody want a demonstration of the look and feel - go visit MySpace.


Partnerringe said:

thanks for the interesting article.

what's wrong with using title-attributes on each input? they are accessible, don't need JS or CSS, and they work on mouseover.

too easy?

Partnerringe said:


thanks for the interesting article.

what's wrong with using title-attributes on each input? they are accessible, don't need JS or CSS, and they work on mouseover.

too easy?

cinsel chat said:

attributes on each input? they are accessible, don't need JS or CSS, and they work on mouseover.

Vivek Deshmukh said:

I saw the following in the Hint of Passowrd in your demo link @ (http://www.askthecssguy.com/examples/formfieldhints/example06.html)

Text reads: "5-13 characters, but not 7. Never 7"

Any particular reason why not number 7? :)

DaiLaughing said:

All that effort and if the fields are near the right hand side of the browser window the hints can't be seen. Plus the fact that title does it for free and CSS can do it almost as quick as title and with any look you want with no need for scripts.

çanta said:

attributes on each input? they are accessible, don't need JS or CSS, and they work on mouseover....Thanks

kale kapı said:

All that effort and if the fields are near the right hand side of the browser window the hints can't be seen. Plus the fact that title does it for free and CSS can do it almost as quick as title and with any look you want with no need for scripts.

justin tv said:

Please help!!! I dont know a lot about HTML or javscript or anything but I am starting my own business and need a website.

lig tv said:

Is there anywhere that the addloadevent code is explained ?

Samuel said:

Very nice, just what I was looking for. And even a bit more. =)
Thanks!
ps. the last letter of the Finnish alphabet is not z, it's ö (ö) =)

günlük altın fiyatları said:

Got a question:
I'm using this script for validation alerts on invalid fields (eg: when a domain name isn't valid, a red exclamation icon appears; hovering the image reveals the tooltip span). Once the field is corrected, I delete the span and reload prepareInputsForHints();
Unfortunatly, hovering the (now a green checkmark) image still tries to fire the tooltip reveal (on a span that no longer exists).
Any thoughts?
It looks like the check for if(inputs[i].parentNode...) still proves true, even though there's no span inside the current DD.

online maçlar said:

I tried using JS but the variables dont get loaded. Help would be appreciated.

danteller said:

This is very cool.

What do you need to do in order to display different tips if there are two inputs on a single line?

betsson said:

it seems like a good article.

oteller said:

Don't take things too seriously. The author was just mentioning the lighter side of programming.

mynak said:

the variables dont get loaded. Help would be appreciated.

derya baykal said:

it's good work!

lauren said:

Howdy CSS guy-
First off... thanks~I have been wanting to incorp this into my forms.
But - I am getting issues with both safari and opera (the hints are appearing ontop of the input field)
Any suggestions?

canlı maç izle said:

Great post, but I think I've encountered a little bug in Safari whereby the hints won't appear when used with radio buttons. They work fine with other input fields. Safari 2.0.4 I'm using.

canlı lig tv izle said:

Excellent tutorial, and some great feeback in the comments.

To stefan: I'd be tempted to use the title tag too, but in our experiments @ work, the title tag only allows a maximum of 255 characters in some browsers. Also, adding extra markup to the title tag (such as strong tags, paragraphs etc.) behaves oddly in older browers.

amerikan kapı said:

Hi, nice web - site, and thanks a lot for all the useful informations, kind greetings from germany

sohbet said:

Thankss .

sohbet sitesi said:

Thnk you my admin

sohpet said:

But - I am getting issues with both safari and opera (the hints are appearing ontop of the hehe:D

lig tv izle said:

It cut off a portion of my post. You can create an array of form elements to look for input and select respectively and loop over that rather than coding the same thing twice. DRY.

Sezgin said:

This is pretty cool, it'll be nice when ie 6 and other browsers that might not support this are no longer a sizable %.

Bayerischer Wald said:

thank you, this is a very interesting article.

we using title-attributes on each input. what's wrong?
we don't use JavaScript or CSS Styles for this.

it is easy and very useful for everybody !

Propriozeption said:

OK, good article..

very useful for everybody !

Ätherische Öle said:

Thank You!!! This is a very Good Idee! !!

lightlygrilled said:

Hi,

Wonderful css.

Just one thing - my hints have all of a sudden started appearing behind the image they were initially displaying in front off.

Any ideas.....

trauringe said:

I thank for the knowledge

Senior Chat said:

Hi guys,

Wonder if one of you would be good enough to help me out place. I'm using this script on my website that where the input/select boxes are within a table.

Thing is, although the hints display perfectly, the position of the hint doesn't in terms of resolution of the display. For example, under 1024X768 it's fine, but as soon as I start cranking the resolution up the hints move further and further off too the right.

As you can probably tell, this is all new to me, so I'd really appreciate a step-by-step approach to making it work with tables?

Thanks for any help?
Regards
Rob

tercüme said:

nice post! thanks for sharing

Nur Çeyiz ve Evtekstili said:

thank you, this is a very interesting article.

we using title-attributes on each input. what's wrong?
we don't use JavaScript or CSS Styles for this.

it is easy and very useful for everybody !
Nevresim takımı,çeyizlik nevresim, çeyiz söz bohçası, çeyiz bohça, dantel, piko

NurÇeyiz Nevresim Bohça said:

thank you, this is a very interesting article.

we using title-attributes on each input. what's wrong?
we don't use JavaScript or CSS Styles for this.

it is easy and very useful for everybody !
Nevresim takımı,çeyizlik nevresim, çeyiz söz bohçası, çeyiz bohça, dantel, piko, modeller,çeşitler,fiyatlar,desenler,

Nur Çeyiz ve Evtekstili said:

the variables dont get loaded. Help would be appreciated.

piko çeşitleri,havlu kenarı,nevresim modelleri,nevresim çeşitleri,pikolu nevresim,çeyizlik nevresim,ceyizlik,dantel,pike takımı,pike takımları, pike takım, aplike,kaneviçe,nevresimler

Schmuck said:

Very helpful information for our Site. Thank you a lot.

Schmuck said:

Very helpful information, thank you a lot!

MMO said:

thx for the awesome tips CSS guy!

webdesign Düsseldorf said:

thanks good article

promosyon çanta said:

Thanks for good article.

CelikKapi said:

nice job thank you :)

CelikKapi said:

nice job thank you :)

Mihai Vigariu said:

Now, that's what i call one step to step tutorial! :)

Thanks for your time, i will implement this on my website.

Mihai

Silber kaufen said:

Thx you for this helpful information and great stuff! nice knowledge

Jonathan said:

This script does not work when there is a body onload focus function.

shaun t insanity said:

Thanks for this useful script. I will be implemented on my new site.

Thanks.

the passion for programming said:

Nice work, thanks for sharing.

the passion for programming said:

Nice work, thanks for sharing.

insanity workout said:

Any applications for safari...

Schwarzenbek said:

Great work.Thank for the knowledge

Strom Anbieter said:

yes still great work and good stuff. greetings

mzu said:

This script would make a great addition to my simple editor - however, I'm having problems getting fckeditor to accept it - no problem with the other form elements - any clues?

thanks for sharing.

ilahi dinle said:

Any applications for safari.

Strand reise billig said:

great work !
that helped me a lot

Gold verkaufen said:

i agree with you. good stuff and great work!

Zzzella said:

This was awesome and took 5 mins to integrate into my code.. so thanks!
I found having to add dl,dt,dd everywhere into old code time consuming so I rewrote it to work with prototype attribute selectors. Hope it will be helpful to someone.

The below works by a span and setting the title attribute to be the same as the form element id

<span class="hint" title="myid">A hint here<span class="hint-pointer"> </span></span>
<input type="text" name="myname" value="" id="myid" />


function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}

function prepareInputsForHints() {
$$("INPUT,TEXTAREA,SELECT").each(function(inp){
inp.onmouseover = function () {
if(this.id != undefined){
showHint(this.id);
}
}
inp.onmouseout = function () {
if(this.id != undefined){
hideHint(this.id);
}
}
});
}
addLoadEvent(prepareInputsForHints);

function showHint(id){
if(id.length > 0){
$$("SPAN[title="+id+"]").each(function(sp){
sp.style.display = 'inline';
});
}
}

function hideHint(id){
if(id.length > 0){
$$("SPAN[title="+id+"]").each(function(sp){
sp.style.display = 'none';
});
}
}

chat said:

wery nice post and page thanks

kral oyun said:

good shared.. thanks..

 

Post a comment