Rutwick Gangurde Rutwick Gangurde - 1 year ago 59
jQuery Question

Adjust a div's height/width by dragging its left/top border without jQuery draggable?

I've been struggling to achieve this! We don't want an extra dependency hence not using UI draggable.
Whatever I tried is over here:

<div id="cont">
<div id="test">

<div id="test2">

<div id="drag">


And the jQuery code is in the Fiddle.

The first div is under the second. The second one's width is kept to 0, now when I drag the drag bar, I want to adjust the width of this div, revealing its content and thus overlapping the first one's content. My code allows me to drag, but stops after some time and doesn't drag from the right to left!

Any ideas to make it working?

Answer Source

I'm assuming you want a different bar for the vertical resizing.

Some notes of the changes I made:

  • mousemove and mouseup should be bound to a parent element, usually document. JavaScript does not have any sort of capture mouse (like CaptureMouse() in WPF) meaning if the user moves the mouse too quickly and leaves your element then your mouse events will stop being captured by your event handlers. By binding the document you ensure the mouse events within your page will always be captured.
  • Making a reference to your dragable object in the mousedown helps keep you sane.
  • If you want to resize the element you'll also have to change the elements width.
  • If you don't unbind the added mouseup and mousemove bindings they may be added multiple times, later firing as many times.
  • Don't really need drag = true because the mousemove event shouldn't exist at all when the user isn't dragging.
  • In order for the background to continue filling your element after it was resized I changed it's width and height to 100% in the CSS.

Most dragable divs are given an absolute positioning rather then relative. Changing this will also require some changes in the code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download