Reputation: 365
I have 3 textarea with a default text "Write something". Let say if I click on one of them, the default text will disappear and that textarea get focus. However, if I click on another textarea, the default text of another textarea will disappear but the default text of first textarea will reappear. How can I make this happen? Same thing is that if I am to click on the third textarea, its default text of the textarea that I clicked on will disappear and the other will reappear.
Coding:
<textarea class="t" id="tt3">Write something</textarea>
<textarea class="t" id="tt3">Write something</textarea>
<textarea class="t" id="tt3">Write something</textarea>
How can I do that with jQuery?
Upvotes: 0
Views: 116
Reputation: 67832
Consider using the HTML5 placeholder attribute and falling back on a javascript solution if the browser doesn't support that attribute.
Upvotes: 0
Reputation: 679
First, you declare a css with some classes:
.t {
font-family: Helvetica, Geneva, Arial, sans-serif;
}
.txt-selected {
font-style: normal;
}
.txt-unselected {
font-style: italic;
}
Then, in javascript you write:
$(document).ready(function () {
var defaultText = "write something";
$(".t")
.addClass("txt-unselected")
.val(defaultText)
.focus(function () {
var $this = $(this);
if($this.val() == defaultText)
{
$this.val("");
$this.removeClass("txt-unselected");
$this.addClass("txt-selected");
}
})
.blur(function () {
var $this = $(this);
if($this.val() == "")
{
$this.removeClass("txt-selected");
$this.addClass("txt-unselected");
$this.val(defaultText);
}
});
});
That should do the work. ;)
Upvotes: 1
Reputation: 7773
This should do it for ya!
http://www.jsfiddle.net/86TTc/1/
I've tested this across a fairly wide-range of browsers (the same ones that jQuery supports). I may have missed one or two, but this should get you 99.9% of the way there.
I hope this helps you both with your specific task, and helps you understand how it is done.
Upvotes: 0
Reputation: 3167
What you are talking about (I think) is often referred to as a watermark.
Take a look at this: http://code.google.com/p/jquery-watermark/
Upvotes: 1