Very simple textbox watermark using JQuery 17
If you haven’t heard about JQuery by now, I strongly suggest you go check it out. It is a very powerful cross-browser JavaScript library that simplifies a lot of the script I have to write, and even more interesting is the fact that Microsoft is going to start distributing it as well with Visual Studio and ASP .NET MVC. I had a post very similar to this one on my blog before, but since it got lost, I decided to go ahead and post it again, slightly improved over the last version.
The idea here is to be simple, and do this in just a few lines of JavaScript. I’m not here to teach all of the intricacies of JQuery, as that can best be explained by the documentation on their website.
I’ll start by displaying the HTML element that we will be manipulating:
1 | <input type="text" id="textBox1" class="watermarkOn" value="Type here" /> |
The CSS class on that element is really simple and defines the look of the textbox when the watermark is active:
Now to write the script that does all of the action. I will assume that you’ve already set up the JavaScript include for JQuery on the page:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | $(document).ready(function() { // Define what happens when the textbox comes under focus // Remove the watermark class and clear the box $("#textBox1").focus(function() { $(this).filter(function() { // We only want this to apply if there's not // something actually entered return $(this).val() == "" || $(this).val() == "Type here" }).removeClass("watermarkOn").val(""); }); // Define what happens when the textbox loses focus // Add the watermark class and default text $("#textBox1").blur(function() { $(this).filter(function() { // We only want this to apply if there's not // something actually entered return $(this).val() == "" }).addClass("watermarkOn").val("Type here"); }); }); |
And that’s all there is to it! If you’re using this on your site, you’ll probably want to do a bit more customization and such, but these are the basics. I skimmed over a lot of the fine details, I know, but there really isn’t much more to it than this.
