While working on some javascript for a billing and delivery address form, I used;
document.getElementById(itm.name + "Hint").style.visibility = 'hidden';
to successfully toggle visibility of a element containing a hint for the field if its left empty. The problem, when the hint disappeared, the space it occupied didn't! After some head scratching I looked at some earlier code I had written which hid all the fields for delivery address when the user ticks "Deliver to Billing Address", I realised I had used instead;
document.getElementById(itm.name + "Hint").style.display = 'none';
This is my outline show/ hide function which fires from the input fields onkeyup event. I use a regular expression to ignore whitespace typed into the field
var notEmpty = /^\s*$/; // Match all whitespace
function isFieldEmpty(itm) {
if(notEmpty.test(itm.value)) {
document.getElementById(itm.name + "Hint").style.display = 'inline'; // Hint visible
} else {
document.getElementById(itm.name + "Hint").style.display = 'none'; // Hint hidden
}
}
This is the html for the field & containing the field hint. You can try this yourself by typing some text after the hint, and watching it move up into the space occuppied by the hint as soon as you type any character into the first name field.
<input name="firstName" type="text" tabindex="1" value="" onkeyup="isFieldEmpty(this)" />
<span id="firstNameHint" class="hint"><br />Please type a first name</span>
Update 24 Sept 14: Having noted the downvotes and read the question this is a duplicate of, please accept my apologies. The earlier question didn't flag up in the list of possible questions when I was typing it, and I created it in the context of wanting to toggle display of temporary text, which isn't covered by earlier question.