ajaxy_page.html 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4. <form action="javascript:updateDom()">
  5. <label for="typer">New label text:</label>
  6. <input name="typer" type="text"/>
  7. <br/>
  8. <label for="color">Select label color:</label>
  9. <input name="color" id="red" value="red" type="radio"/>Red
  10. <input name="color" id="green" value="green" type="radio"/>Green
  11. <br/>
  12. <input name="submit" type="submit" value="Add Label"/>
  13. </form>
  14. <div id="update_butter" style="display:none"></div>
  15. <script>
  16. var butter = document.getElementById('update_butter');
  17. var textProperty = butter['innerText'] ? 'innerText' : 'textContent';
  18. var listeners = [];
  19. function registerListener(fn) {
  20. listeners.push(fn);
  21. }
  22. function updateDom() {
  23. butter.style.display = 'block';
  24. butter[textProperty] = 'Updating';
  25. disableForm();
  26. tick();
  27. }
  28. function disableForm() {
  29. var inputs = document.getElementsByTagName('input');
  30. for (var i = 0, input; input = inputs[i]; ++i) {
  31. input.disabled = true;
  32. }
  33. }
  34. function enableForm() {
  35. var inputs = document.getElementsByTagName('input');
  36. for (var i = 0, input; input = inputs[i]; ++i) {
  37. input.disabled = false;
  38. }
  39. }
  40. function tick() {
  41. var length = butter[textProperty].substring('Updating'.length).length;
  42. if (length != 10) {
  43. butter[textProperty] += '.';
  44. window.setTimeout(tick, 500);
  45. } else {
  46. enableForm();
  47. var div = document.createElement('div');
  48. var colors = document.forms[0].color;
  49. for (var i = 0, color; color = colors[i]; ++i) {
  50. if (color.checked) {
  51. div.style.backgroundColor = color.value;
  52. break;
  53. }
  54. }
  55. div[textProperty] = document.forms[0].typer.value;
  56. div.className = 'label';
  57. document.forms[0].typer.value = '';
  58. document.body.appendChild(div);
  59. butter[textProperty] = 'Done!';
  60. window.setTimeout(function() {
  61. while (listeners.length) {
  62. try {
  63. listeners.shift()(div[textProperty]);
  64. } catch (e) {
  65. butter[textProperty] = "Exception seen: " + e;
  66. }
  67. }
  68. }, 500);
  69. }
  70. }
  71. </script>
  72. </body>
  73. </html>