3
I am 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>
<div id="cloud_main_page">
<div class="cloud_mouse_selection"></div>
</div>
It works well, as long as the user drags the mouse only from left to right and top to bottom, and this obviously won’t always be the same scenario... So, how could I do if the user decides to drag the mouse in different directions?
This code is still capable of improvement, however I limited myself to answer the question, if you want extra help at any time, my contact is in my portfolio
– Wagner Kramer