Toggles instructional and default copy text and styles


/ Published in: JavaScript
Save to your folder(s)

This utility function attaches listeners to a text field or text area. It supports default text for instructional copy. The original text in the field is used as the instructional/default text. When the box gets focus, it disappears and the user can type. If the focus is lost and the box is empty, the original text will be placed again.

The method also swaps CSS class if the class names are passes as arguments. There is one class for default text, and one for user text.
This is optional.

Usage:
Create a text field in HTML. For example, use parameters:

input type="text" id="t1" class="textFieldDefault iCopy" value="Type something here"

Then in script block:

sl_addClearCopyListeners(document.getElementById("t1"), 'iCopy' , 'noCopy');

// or without CSS classes:
sl_addClearCopyListeners(document.getElementById("t1"));
'noCopy');


Copy this code and paste it in your HTML
  1. /**
  2.  * Add instructional copy support for text fields and text area.
  3.  * The method will clear the copy, and swap styles.
  4.  *
  5.  * @param textField the text element that will be enhanced.
  6.  * @param copyClass class used for instructional copy
  7.  * @param noCopyClass class used for plain text
  8.  */
  9.  
  10. function sl_addClearCopyListeners (textField, copyClass, noCopyClass){
  11.  
  12. // set default value in the object itself
  13. textField.originalCopy = textField.value;
  14. textField.copyClass = copyClass;
  15. textField.noCopyClass = noCopyClass;
  16.  
  17. // add listiners
  18. textField.onfocus = function(){
  19. if (this.value == this.originalCopy){
  20. this.value = '';
  21. sl_replaceClass(this, this.copyClass, this.noCopyClass);
  22. return false;
  23. }
  24. return true;
  25. };
  26.  
  27. textField.onblur = function(){
  28. if (this.value == ''){
  29. sl_replaceClass(this, this.noCopyClass, this.copyClass);
  30. this.value = this.originalCopy;
  31. return false;
  32. }
  33. return true;
  34. };
  35. };
  36.  
  37. /**
  38.  * Replace a class with another, leaving other classes untouched.
  39.  * If the class does not exist, nothing will happen.
  40.  *
  41.  * @param domElement the text element that will be enhanced.
  42.  * @param oldClass class to replace
  43.  * @param newClass the replacement class
  44.  */
  45. function sl_replaceClass(domElement, oldClass, newClass){
  46. var elementClass = '' + domElement.className;
  47. // save some work, avoid flashing
  48. if (elementClass.indexOf(oldClass) > -1){
  49. elementClass = elementClass.replace(oldClass , newClass);
  50. domElement.className = elementClass;
  51. }
  52. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.