JSFiddle - React, Tailwind, and code Playground

by Wendigooor

JavaScript

function FloatingSquare(top, left, sideLength, color){
    var self = this;
    
    _top = top;
    _left = left;    
    
    var _moving = false;
    var _oldLeft;
    var _oldTop;
    
    _body = $('body')
    _body.css({position:'relative'})
    
    this.square = $('<span></span>');
    this.square.css({
        top: top,
        left: left,
        width: sideLength,
        height: sideLength,
        position: 'absolute',
        backgroundColor: color
    });
    this.square.appendTo(_body)
    
    
    this.square.on('click', function(e){
        if(_moving){
            _moving = false;
        } else{
            _moving = true;
            _oldLeft = e.clientX;
            _oldTop = e.clientY;
        }
    });
    
    
    _body.on('mousemove', function(e){
        console.log(_moving)
        if(_moving){
            self.square.css({
                top: self.top() + (e.clientY - _oldTop),
                left: self.left() + (e.clientX - _oldLeft)
            });
            
            _oldTop = e.clientY;
            _oldLeft = e.clientX;
        }
    
    });
    
    this.top = function(){
        return this.square.position().top;
    }
    
    this.left = function(){
        return this.square.position().left;
    }

}

var a = new FloatingSquare(100, 100, 50, 'red')