I'm developing the following code to create an element selection area using the mouse.
var draggingMouse = false;
var leftMouseDrag, topMouseDrag;
$(document).on("mousedown mouseup", "#cloud_main_page", function(e){
if (e.type == "mousedown") {
draggingMouse = true;
var offset = $(this).offset();
leftMouseDrag = e.pageX - offset.left;
topMouseDrag = e.pageY - offset.top
$("#cloud_main_page .cloud_mouse_selection").css({"top": topMouseDrag, "left" : leftMouseDrag});
} else{
draggingMouse = false;
$("#cloud_main_page .cloud_mouse_selection").removeAttr("style");
}
}).on("mousemove", "#cloud_main_page", function(e){
if(draggingMouse){
var offsetDrag = $("#cloud_main_page .cloud_mouse_selection").offset();
var top = e.pageY - offsetDrag.top;
var left = e.pageX - offsetDrag.left;
var width = Math.abs(left);
var height = Math.abs(top);
$("#cloud_main_page .cloud_mouse_selection").css({"width": width, "height": height});
}
});
#cloud_main_page{
width:400px;
height:400px;
position:relative;
}
#cloud_main_page .cloud_mouse_selection{
position:absolute;
background-color:rgba(6, 217, 160, 0.05);
border: 1px solid rgba(6, 217, 160, 0.3);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="cloud_main_page">
<div class="cloud_mouse_selection"></div>
</div>
It works fine as long as the user drags the mouse from Left to Right and from top to bottom, and this obviously will not always be the same scenario ... So how could I do it if the user decides to drag the mouse on different directions?