jquery.sortable.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * HTML5 Sortable jQuery Plugin
  3. * http://farhadi.ir/projects/html5sortable
  4. *
  5. * Copyright 2012, Ali Farhadi
  6. * Released under the MIT license.
  7. */
  8. (function($) {
  9. var dragging, placeholders = $();
  10. $.fn.sortable = function(options) {
  11. options = options || {};
  12. return this.each(function() {
  13. if (/^enable|disable|destroy$/.test(options)) {
  14. var items = $(this).children($(this).data('items')).attr('draggable', options == 'enable');
  15. options == 'destroy' && items.add(this)
  16. .removeData('connectWith').removeData('items')
  17. .unbind('dragstart.h5s dragend.h5s selectstart.h5s dragover.h5s dragenter.h5s drop.h5s');
  18. return;
  19. }
  20. var index, items = $(this).children(options.items), connectWith = options.connectWith || false;
  21. var placeholder = $('<' + items[0].tagName + ' class="sortable-placeholder">');
  22. var handle = options.handle, isHandle;
  23. items.find(handle).mousedown(function() {
  24. isHandle = true;
  25. }).mouseup(function() {
  26. isHandle = false;
  27. });
  28. $(this).data('items', options.items)
  29. placeholders = placeholders.add(placeholder);
  30. if (connectWith) {
  31. $(connectWith).add(this).data('connectWith', connectWith);
  32. }
  33. items.attr('draggable', 'true').bind('dragstart.h5s', function(e) {
  34. if (handle && !isHandle) {
  35. return false;
  36. }
  37. isHandle = false;
  38. var dt = e.originalEvent.dataTransfer;
  39. dt.effectAllowed = 'move';
  40. dt.setData('Text', 'dummy');
  41. dragging = $(this).addClass('sortable-dragging');
  42. index = dragging.index();
  43. }).bind('dragend.h5s', function() {
  44. dragging.removeClass('sortable-dragging').fadeIn();
  45. placeholders.detach();
  46. if (index != dragging.index()) {
  47. items.parent().trigger('sortupdate');
  48. }
  49. dragging = null;
  50. }).not('a[href], img').bind('selectstart.h5s', function() {
  51. this.dragDrop && this.dragDrop();
  52. return false;
  53. }).end().add([this, placeholder]).bind('dragover.h5s dragenter.h5s drop.h5s', function(e) {
  54. if (!items.is(dragging) && connectWith !== $(dragging).parent().data('connectWith')) {
  55. return true;
  56. }
  57. if (e.type == 'drop') {
  58. e.stopPropagation();
  59. placeholders.filter(':visible').after(dragging);
  60. return false;
  61. }
  62. e.preventDefault();
  63. e.originalEvent.dataTransfer.dropEffect = 'move';
  64. if (items.is(this)) {
  65. dragging.hide();
  66. $(this)[placeholder.index() < $(this).index() ? 'after' : 'before'](placeholder);
  67. placeholders.not(placeholder).detach();
  68. }
  69. return false;
  70. });
  71. });
  72. };
  73. })(jQuery);