Combining mousedown and mousemove events together with Javascript (JQUERY?)
- by webzide
Dear experts,
I would like to combine a the mousedown and mousemove and mouseup events together.
Basically the application of this would be making a UI for selecting elements. Like selecting icons in windows when the mouse is clicked down and as you move it, a dotted border dynamically moves with it.
I know this is possible with the predefined UI of Jquery.
But I am building a web application that requires the integration of this and would like to know the technique.
I spend hours on this and it just doesn't work.
here's is the code i have so far and the logic behind it:
$(document).bind('mousedown', function (evt) {
evt = (evt) ? evt : event;
startX = evt.clientX;
startY = evt.clientY;
div = document.createElement("div");
div.style.position = "absolute";
div.style.left = startX + "px";
div.style.top = startY + "px";
div.style.border = "1px dotted #DDDDDD";
$(document).bind('mousemove', function(evt){
evt=(evt) ? evt: event;
alert("TESTING OF THIS WORKS");
});
});
$(document).bind('mouseup',function(evt) {
var evt = (evt) ? evt : event;
var endX = evt.clientX;
var endY = evt.clientY;
difX = (endX - startX);
difY = (endY - startY)
if ((difX || difY) > 0) {
div.style.width = difX + "px";
div.style.height = difY + "px";
document.body.appendChild(div);
}
$(this).unbind('mousemove');
});
As you can see I have placed an event binding of mousemove into the event function of mousedown so that it can only be invoked when the mouse is down.
but the problem is, once that event is binded, it does not come off. The borders does not move dynamically as expected.
Maybe my logic is entirely messed up.
If anyone could point me the the right direction that would be great.
THanks in advance.