Advertisement
Guest User

Untitled

a guest
Aug 4th, 2015
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. // bug - on each click this code creates a new event listener for all $drag parents
  2. // serious lack of memory and permormance
  3. // solution - unbind this event on 'mouseup' and make 'mouseup' once-executable via one()
  4.  
  5. (function($) {
  6. $.fn.drags = function(opt) {
  7.  
  8. opt = $.extend({handle: '', cursor: 'move'}, opt);
  9.  
  10. if(opt.handle === '') {
  11. var $el = this;
  12. } else {
  13. var $el = this.find(opt.handle);
  14. }
  15.  
  16. return $el.css('cursor', opt.cursor).on('mousedown', function(e) {
  17. if(opt.handle === '') {
  18. var $drag = $(this).addClass('draggable');
  19. } else {
  20. var $drag = $(this).addClass('active-handle').parent().addClass('draggable');
  21. }
  22.  
  23. var z_idx = $drag.css('z-index'),
  24. drg_h = $drag.outerHeight(),
  25. drg_w = $drag.outerWidth(),
  26. pos_y = $drag.offset().top + drg_h - e.pageY,
  27. pos_x = $drag.offset().left + drg_w - e.pageX;
  28.  
  29. // bind first event
  30. // why parents() ?
  31. $drag.css('z-index', 1000).parents().on('mousemove.drags', function(e) {
  32. $('.draggable').offset({
  33. top:e.pageY + pos_y - drg_h,
  34. left:e.pageX + pos_x - drg_w
  35. }).one('mouseup', function() {
  36. $(this).removeClass('draggable').css('z-index', z_idx);
  37.  
  38. // unbind first event
  39. $drag.parents().unbind('mousemove.drags');
  40. });
  41. });
  42. e.preventDefault(); // disable selection
  43.  
  44. }).on('mouseup', function() {
  45. if(opt.handle === '') {
  46. $(this).removeClass('draggable');
  47. } else {
  48. $(this).removeClass('active-handle').parent().removeClass('draggable');
  49. }
  50. });
  51.  
  52. }
  53. })(jQuery);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement