upload.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. (function($, undefined) {
  2. 'use strict';
  3. window.VAMTAM = window.VAMTAM || {};
  4. window.VAMTAM.upload = {
  5. init: function() {
  6. var file_frame;
  7. $(document).on('click', '.vamtam-upload-button', function(e) {
  8. var field_id = $(this).attr('data-target');
  9. file_frame = wp.media.frames.file_frame = wp.media({
  10. multiple: false,
  11. library: {
  12. type: $(this).hasClass('vamtam-video-upload') ? 'video' : 'image'
  13. }
  14. });
  15. file_frame.on( 'select', function() {
  16. var attachment = file_frame.state().get('selection').first();
  17. window.VAMTAM.upload.fill(field_id, attachment.attributes.url);
  18. });
  19. file_frame.open();
  20. e.preventDefault();
  21. });
  22. $(document).on('click', '.vamtam-upload-clear', function(e) {
  23. window.VAMTAM.upload.remove($(this).attr('data-target'));
  24. e.preventDefault();
  25. });
  26. $(document).on('click', '.vamtam-upload-undo', function(e) {
  27. window.VAMTAM.upload.undo($(this).attr('data-target'));
  28. e.preventDefault();
  29. });
  30. },
  31. fill: function(id, str) {
  32. if (/^\s*$/.test(str)) {
  33. window.VAMTAM.upload.remove(id);
  34. return;
  35. }
  36. var target = $('#' + id);
  37. target.data('undo', target.val());
  38. target.val(str);
  39. target.siblings('.vamtam-upload-clear, .vamtam-upload-undo').css({
  40. display: 'inline-block'
  41. });
  42. window.VAMTAM.upload.preview(id, str);
  43. },
  44. preview: function(id, str) {
  45. $('#' + id + '_preview').parents('.upload-basic-wrapper').addClass('active');
  46. $('#' + id + '_preview').find('img').attr('src', str).css({
  47. display: 'inline-block'
  48. });
  49. },
  50. remove: function(id) {
  51. var inp = $('#' + id);
  52. $('#' + id + '_preview').find('img').attr('src', '').hide();
  53. $('#' + id + '_preview').parents('.upload-basic-wrapper').removeClass('active');
  54. inp.data('undo', inp.val()).val('')
  55. .siblings('.vamtam-upload-undo').css({
  56. display: 'inline-block'
  57. })
  58. .siblings('.vamtam-upload-clear').hide();
  59. },
  60. undo: function(id) {
  61. var inp = $('#' + id);
  62. this.preview(id, inp.data('undo'));
  63. inp.val(inp.data('undo'));
  64. inp.data('undo', '').siblings('.vamtam-upload-undo').hide();
  65. var remove = inp.siblings('.vamtam-upload-clear');
  66. if (inp.val().length === 0 && remove.is(':visible')) {
  67. remove.hide();
  68. } else if (inp.val().length > 0 && remove.is(':hidden')) {
  69. remove.css({
  70. display: 'inline-block'
  71. });
  72. }
  73. }
  74. };
  75. })(jQuery);