Friday 7 October 2011

JavaScript: delete default text when selecting a textarea (onblur and onfocus)

   


Today we are going to create a textarea with a simple effect. We want to obtain the following:



The text inside the textarea will disappear when the area is selected, and reappear when the area is not selected and there's no text inside it. To do so, we are going to use JavaScript.

Ready for the code? Ok, let's go.


The HTML
First of all I would like to show you the HTML:
<textarea class="notselected" id="textarea" onfocus="change('selected'); empty();" onblur="change('notselected'); empty();">Add your comment here...</textarea>
A few notes on that:
1) the starting class is "notselected" because our textarea is not selected yet;
2) the id is "textarea" (straight and simple!);
3) on focus we will change the class of the textarea to "selected" and empty it;
4) on blur we will change the class of the textarea to "notselected" and eventually repopulate it.
The magic is done by a two small JavaScript functions.

The JavaScript
The code is very simple and I will explain it line by line:
<script language="JavaScript" type="text/javascript">
function empty() {
  var ta = document.getElementById("textarea");
  if (ta.getAttribute("class") == "notselected" && ta.value == "") ta.value = "Add your comment here...";
  if (ta.getAttribute("class") == "selected") ta.value = "";
}
function change(cls) {
  document.getElementById("textarea").setAttribute("class", cls);
}
</script>
The first function is called empty (even if it deletes the content of the textarea on certain conditions).
With document.getElementById we select our textarea.

If the textarea has a class equal to "notselected" and its value is empty, we fill the textarea with the default text ("Add your comment here...").

If the  textarea has a class equal to "selected", the function will delete its content.

The second function is changing the attribute "class" according to the passed parameter. We basically switch the textarea class between "selected" and "notselected" in order to empty it when needed.

And that is all. As usual, the above example should be considered as a starting point or, if you prefer, as an experiment made to understand what's behind those magic tricks we see on the web everyday.
The textarea for instance, could be styled and the text could change its color according to what's inside (when the value is default should be grey, when it is changed by the user should be black). Can you think of an appropriate way to achieve that? Share your thoughts in the comment section below!


4 comments:

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.