Watermark implementation using javascript

How to add water mark to Text Boxes using JavaScript

Water mark or placeholder for Input Text Boxes is one of the ways of providing a hint to the user about what to enter in a text box.

‘input’ tag for HTML does have an attribute named ‘placeholder’ to serve this purpose but this is not supported by older versions mainly IE browser.

To achieve this functionality we can make use of JavaScript functions :

Set value attribute to the input tag with desired text : value=”Value as Watermark”.

Implement 2 functions ‘onblur’ and ‘onfocus’:

In input tag :

    onblur="blurInput('textBoxId','Value as Watermark');"
    onfocus="focusInput('textBoxId','Value as Watermark');"

In JavaScript :

   function blurInput(inputValue, waterMarkText) {
        if ($("#" + inputValue).val() == '') {
            $("#" + inputValue)
            .val(waterMarkText)
            .addClass('waterMark');
        }
    }

    function focusInput(inputValue, waterMarkText) {
        if ($("#" + inputValue).val() == waterMarkText) {
            $("#" + inputValue).val('')
            .removeClass('waterMark');
        }
    }

An option for definition of the onblur event :

    function blurInput(inputValue, waterMarkText) {
        if ($("#" + inputValue).val() == '') {
            $("#" + inputValue)
            .val(waterMarkText)
            .addClass('waterMark');
        }
        else{
            callToAnotherFunc();
        }
    }

Happy Coding 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s