script.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. console.clear();
  2. 'use strict';
  3. function validateText(value) {
  4. return value !== '' ? true : false;
  5. }
  6. function sendToServer(value) {
  7. console.log('Send to server', value);
  8. }
  9. $('body').on('click', '[editable]', function(event){
  10. event.preventDefault(); // сбросили поведение элементов по молчанию, если была бы ссылка она бы не работала (защита от дурака)
  11. var $element = $(this);
  12. var type = $element.attr('editable');
  13. var $firstButton = $('#firstButton');
  14. var $secondButton = $('#secondButton');
  15. $firstButton.show();
  16. $secondButton.show();
  17. function hideButton(){
  18. $firstButton.hide();
  19. $secondButton.hide();
  20. }
  21. var events = {
  22. before: $element.attr('onbeforesave') ? $element.attr('onbeforesave') : null,
  23. after: $element.attr('onaftersave') ? $element.attr('onaftersave') : null
  24. };
  25. function onEdit() {
  26. $element
  27. .text( $(this).val() )
  28. .insertAfter(this);
  29. events.after && window[events.after]( $(this).val() );
  30. $(this).remove();
  31. }
  32. var $inp = $('<input>')
  33. .attr('type', type)
  34. .val( $element.text() )
  35. .insertAfter($element)
  36. .focus()
  37. .select()
  38. .after( $secondButton )
  39. .after( $firstButton );
  40. $inp
  41. .on('keyup', function(event) { // обработчик событий на элементе и проверяем клавиши 13 -энтер, 27 -эск
  42. if (event.which === 13) {
  43. if (events.before) {
  44. var valid = window[events.before]( $(this).val() );
  45. if (valid) {
  46. onEdit.call(this);
  47. hideButton();
  48. }
  49. } else {
  50. onEdit.call(this);
  51. hideButton();
  52. }
  53. } else if (event.which === 27) { //27 код клавиши esc
  54. $element.insertAfter(this);
  55. $(this).remove(); // ремув удаляет обработчик событий вместе с элементом
  56. hideButton();
  57. }
  58. })
  59. $element.remove();
  60. $firstButton.one('click', function() {
  61. onEdit.call($inp);
  62. hideButton();
  63. event.stopPropagation();
  64. })
  65. $secondButton.one('click', function() {
  66. $element.clone().insertAfter($inp.val( $element.text() ) );
  67. $inp.remove(); // ремув удаляет обработчик событий вместе с элементом
  68. event.stopPropagation();
  69. hideButton();
  70. })
  71. })