Tuesday, November 18, 2008

Creating Watermarks on Textboxes using Javascript

Anymore watermarks are becoming more and more popular on websites. WaterMarks help to save space and can give a user more guidance than just the label does. I use watermarks to save space and give the proper format. For instance I may label a textbox "Phone" and place the watermark within the text box as "#-###-###-####" When the user click or tabs into the box it removes the watermark. If the users clicks or tabs out of the text box I check for a blank and then replace the watermark otherwise I leave the text alone.

The code I use is only javascript and I add a attribute named "WaterMark" to the textbox. An example would be

<input value="" id="myTextBox" WaterMark="#-###-###-####" type="text">



Below is the Javascript functions. Add them to your page within <script> tags or to your .js file.

function SetWaterMarks() {
var inputs = document.getElementsByTagName('input');

for (var f = 0; f < inputs.length; f++) {
var input = inputs[f]
if (input.type != 'text') continue;
if (input.getAttribute('WaterMark') != null) {
input.onfocus = function() { WaterMarkOff(this); }
input.onblur = function() { WaterMarkOn(this); }
if (input.value == '') {
WaterMarkOn(input);
}
}
else {
input.style.backgroundColor = '';
}
}
}
function WaterMarkOn(obj) {
if (obj.value == '') {
obj.style.color = 'silver';
obj.value = obj.getAttribute("WaterMark");
}
}
function WaterMarkOff(obj) {

if (obj.value == obj.getAttribute("WaterMark")) {
obj.style.color = '';
obj.value = '';

}
}
function ClearWaterMarks() {
var inputs = document.getElementsByTagName('input');
for (var f = 0; f < inputs.length; f++) {
var input = inputs[f]
if (input.type != 'text') continue;
if (input.getAttribute('WaterMark') != null) {
if (input.value == input.getAttribute('WaterMark')) {
input.value = '';
}
}
}
//return true;
}
SetWaterMarks();




When the page loads it will search the page for "text" boxes and look for a WaterMark attribute. If it finds th watermark attribute it will apply the water mark. The only thing left to do is to clear the watermarks prior to postback. The ClearWaterMarks() function will do that for you but you must place it on the form submit function or on the onclick event of the button that is expected to be used.

To Add or Create a watermark on a textbox could not be easier.
Hope this helps someone, it is much lighter than other versions I have seen.

No comments:

Post a Comment