Simple draggable class


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. /**
  2.  * Make any html element draggable.
  3.  *
  4.  * @constructor
  5.  * @param {Object} element Any html element
  6.  * @param {Object} [options] Available options
  7.  * @config {String} [axis] Forces element to move only vertically or horizontally.
  8.  * Possible values: 'x' for horizontal movement, 'y' for vertical movement. Example { 'axis': 'x' }.
  9.  *
  10.  */
  11. function Draggable(element, options){
  12. this.el = element;
  13. this.o = options;
  14. this.el.position = { x: parseInt($(element).css('left')), y: parseInt($(element).css('top')) };
  15. this._canMove = false;
  16. this._init();
  17. }
  18.  
  19. Draggable.prototype = {
  20. _offset: { x: 0, y: 0 },
  21. _init: function(){
  22. $(this.el).bind('mousedown', $.proxy(this._mousedown, this));
  23. $(document).bind('mousemove', $.proxy(this._mousemove, this));
  24. $(document).bind('mouseup', $.proxy(this._mouseup, this));
  25. },
  26. _mousedown: function(e){
  27. e.preventDefault();
  28. this._canMove = true;
  29. this._offset.x = $(this.el).offset().left - e.pageX;
  30. this._offset.y = $(this.el).offset().top - e.pageY;
  31. },
  32. _mousemove: function(e){
  33. if(this._canMove){
  34. var x = this.o.axis === 'y' ? this.el.position.x : this._offset.x + e.pageX;
  35. var y = this.o.axis === 'x' ? this.el.position.y : this._offset.y + e.pageY;
  36. $(this.el).css({'left': x, 'top': y});
  37. }
  38. },
  39. _mouseup: function(){
  40. this._canMove = false;
  41. }
  42. };

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.