JSFiddle - React, Tailwind, and code Playground

by nakhli

HTML

<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.2.1/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.5.3/backbone-min.js"></script>
Copyright (c) Chaker Nakhli - Source code licensed under the terms of the Apache License, Version 2.
<a href="http://www.javageneration.com/">Back to blog post</a>
<div id="page" style="width:2000px;height:2000px;">
    <div class='shape' />
</div>

CSS

.shape {
    position: absolute;
}

JavaScript

var Shape = Backbone.Model.extend({
    defaults: { x:50, y:50, width:150, height:150, color:'black' },
    setTopLeft: function(x,y) {
        this.set({ x:x, y:y });
    },
    setDim: function(w,h) {
        this.set({ width:w, height:h });
    },
});

var shape = new Shape();

shape.bind('change', function() { 
    $('.shape').css({ left:       shape.get('x'),
                      top:        shape.get('y'),
                      width:      shape.get('width'),
                      height:     shape.get('height'),
                      background: shape.get('color') }); 
});

shape.setTopLeft(100, 300);

var dragging = false;

$('.shape').mousedown(function (e) { 
    dragging = true;
    shape.set({ color: 'gray' }); 
});

$('#page').mouseup(function () { 
    dragging = false;
    shape.set({ color: 'black'}); 
});

$('#page').mousemove(function(e) {
    if(dragging) {
        shape.setTopLeft(e.pageX, e.pageY);
    }
});