Skip to content

Instantly share code, notes, and snippets.

@charlycoste
Last active August 30, 2020 15:41
Show Gist options
  • Save charlycoste/fb5cc2b8ad10b1df5bec1ddbc17eb07f to your computer and use it in GitHub Desktop.
Save charlycoste/fb5cc2b8ad10b1df5bec1ddbc17eb07f to your computer and use it in GitHub Desktop.
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