Accessible Compact Forms


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

adopted from:
http://www.alistapart.com/articles/makingcompactformsmoreaccessible/


Copy this code and paste it in your HTML
  1. function initOverLabels() {
  2. var labels, id, field;
  3. labels = document.getElementsByTagName("label");
  4. for(var i=0; i<labels.length; i++) {
  5. if (labels[i].className == "overlabel") {
  6. id = labels[i].htmlFor || labels[i].getAttribute("for");
  7. if (!id || !(field = document.getElementById(id))) {
  8. continue;
  9. }
  10. labels[i].className = "overlabel-apply";
  11. if (field.value != "") {
  12. hideLabel(field.getAttribute("id"), true);
  13. }
  14. field.onfocus = function() {
  15. hideLabel(this.getAttribute("id"), true);
  16. }
  17. field.onblur = function() {
  18. if (this.value == "") {
  19. hideLabel(this.getAttribute("id"), false);
  20. }
  21. }
  22. }
  23. }
  24. }
  25.  
  26. function hideLabel(field_id, hide) {
  27. var field_for;
  28. var labels = document.getElementsByTagName("label");
  29. for(var i=0; i<labels.length; i++) {
  30. field_for = labels[i].htmlFor || labels[i].getAttribute("for");
  31. if (field_for == field_id) {
  32. labels[i].style.textIndent = (hide) ? "-9999px" : "0";
  33. }
  34. }
  35. }
  36.  
  37. window.onload = function() {
  38. initOverLabels();
  39. }
  40.  
  41.  
  42. form#login {
  43. position: relative;
  44. }
  45. div#username, div#password {
  46. position: relative;
  47. float: left;
  48. margin-right: 3px;
  49. }
  50. input#username-field, input#password-field {
  51. width: 10em;
  52. }
  53. label.overlabel {
  54.  
  55. }
  56. label.overlabel-apply {
  57. position: absolute;
  58. top: 3px;
  59. left: 5px;
  60. z-index: 1;
  61. }
  62.  
  63.  
  64. <form name="login" action="#" method="post">
  65. <div id="username">
  66. <label for="username-field" class="overlabel">Username</label>
  67. <input id="username-field" type="text" name="username" title="Username" value="" tabindex="1" />
  68. </div>
  69. <div id="password">
  70. <label for="password-field" class="overlabel">Password</label>
  71. <input id="password-field" type="password" name="password" title="Password" value="" tabindex="2" />
  72. </div>
  73. <div id="submit">
  74. <input type="submit" name="submit" value="Login" tabindex="3" />
  75. </div>
  76. </form>

URL: http://jsfiddle.net/rYp59/3/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.