Skip to content

Instantly share code, notes, and snippets.

@charlycoste

charlycoste/movable.coffee

Last active Aug 30, 2020
Embed
What would you like to do?
Movable HTML bloc with BackboneJS
class Movable extends Backbone.View
events:
'mousedown': 'grab'
'mouseup': 'release'
'mouseleave': 'release'
'mousemove': 'move'
'mouseover': -> @$el.css 'cursor', 'grab'
move: (e)->
return unless @moving
@x = e.pageX - @catching.x + @offset.x
@y = e.pageY - @catching.y + @offset.y
@$el.css
left: @x
top: @y
return
grab: (e)->
@catching =
x: e.pageX
y: e.pageY
@offset =
x: @$el.position().left
y: @$el.position().top
@$el.css
cursor: 'move'
position: 'relative'
@moving = true
return
release: (e)->
@$el.css
cursor: 'auto'
left: @x
top: @y
@trigger 'position:update',
x: @x
y: @y
@moving = false
return
var Movable = (function() {
class Movable extends Backbone.View {
move(e) {
if (!this.moving) {
return;
}
this.x = e.pageX - this.catching.x + this.offset.x;
this.y = e.pageY - this.catching.y + this.offset.y;
this.$el.css({
left: this.x,
top: this.y
});
}
grab(e) {
this.catching = {
x: e.pageX,
y: e.pageY
};
this.offset = {
x: this.$el.position().left,
y: this.$el.position().top
};
this.$el.css({
cursor: 'move',
position: 'relative'
});
this.moving = true;
}
release(e) {
this.$el.css({
cursor: 'auto',
left: this.x,
top: this.y
});
this.trigger('position:update', {
x: this.x,
y: this.y
});
this.moving = false;
}
};
Movable.prototype.events = {
'mousedown': 'grab',
'mouseup': 'release',
'mouseleave': 'release',
'mousemove': 'move',
'mouseover': function() {
return this.$el.css('cursor', 'grab');
}
};
return Movable;
}).call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment