Flame Stinger
Flame Stinger

Reputation: 139

JS resizable div

I would like to create div element which behaves similar to clicking and dragging on Windows desktop.

So far I my code does the following:

My problem is the resize part. Right now, the div can be expanded in a South East direction only.

Refer to this Fiddle an example.

Play around with the Fiddle example to see what I mean (you cannot expand vertically beyond origin, for example).

The reason, I assume, is becuase newX and newY are negative values. How can I solve this?

Upvotes: 1

Views: 1311

Answers (1)

Suhas Bhattu
Suhas Bhattu

Reputation: 551

You haven't consider the case where mouse move coordinates are less than the drawing start coordinates, I have modified the JS code a bit,

var clientBox = document.getElementById("userBox");
var startX, startY, currentX, curentY;

function initRect(event) {
    startX = event.clientX;
    startY = event.clientY;
    window.addEventListener("mousemove", drawRect);
    window.addEventListener("mouseup", dstryRect);

}

function drawRect(event) {
    var width = event.clientX-startX;
    var height = event.clientY-startY;
    var x = startX;
    var y = startY;
    if (width < 0) {
        x = startX + width;
        width=-width;
    }
    if (height < 0) {
        y = startY + height;
        height = -height;
    }
    clientBox.style.display = "block";   // Hideen until click detected
    clientBox.style.top  = y + "px";
    clientBox.style.left = x + "px";
    clientBox.style.width = width + "px";
    clientBox.style.height = height + "px";
}

function dstryRect() {
    window.removeEventListener("mousemove", drawRect);
    window.removeEventListener("mouseup", dstryRect);
    clientBox.style.display = "none";
    clientBox.style.height = "0px";
    clientBox.style.width = "0px";
}

just update these chnages in JS file and you are done. Here is the working fiddle Thanks.

Upvotes: 1

Related Questions