Search code examples
javascripthtmldraggable

Multiple draggable column handles


New to javacsript and first time coding a web from scratch...

Hello all. I'm trying to achieve draggable columns like this js fiddle I found here on stack: http://jsfiddle.net/T4St6/

I succeeded in making it work for my web: http://www.dariusou.com/ but am clueless about how to make multiple columns of that since the script targets the divs specifically (left,right):

var isResizing = false,
lastDownX = 0;

$(function () {
var container = $('#container'),
    left = $('#left'),
    right = $('#right'),
    handle = $('#handle');

handle.on('mousedown', function (e) {
    isResizing = true;
    lastDownX = e.clientX;
});

$(document).on('mousemove', function (e) {
    // we don't want to do anything if we aren't resizing.
    if (!isResizing) 
        return;

    var offsetRight = container.width() - (e.clientX - container.offset().left);

    left.css('right', offsetRight);
    right.css('width', offsetRight);
}).on('mouseup', function (e) {
    // stop resizing
    isResizing = false;
});
});

Would this code be convenient to achieve what I want, or should I look for another code to work from? (I cant write scripts from scratch yet) What I'm trying to achieve is just this kind of draggable columns with handles, but multiple of them, like the image attached to this post. enter image description here

Ideally I would also like to achieve a random drag position for each of these divs( on every load )in the future.(see attached)

enter image description here


Solution

  • First you change your handle to a class:

    <div id='handle' class="handle"></div>
    

    Define your class behavior:

    $('.handle').on('mousedown', function (e) {
         target = e.target.id; //store the id
         isResizing = true;
         lastDownX = e.clientX;
    });
    

    Add more div:

    <div id="left2"> This is the left side's content! </div>
        <!-- Right side -->
        <div id="right2">
            <!-- Actual resize handle -->
            <div id='handle2' class="handle"></div> This is the right side's content!
        </div>
    

    Resize depend on target handle:

    if(target == 'handle'){
         left.css('right', offsetRight);
         right.css('width', offsetRight);
    } else if(target == 'handle2'){
         left2.css('right', offsetRight);
         right2.css('width', offsetRight);
    }
    

    Check this fiddle: jsfiddle.net/T4St6/292/,there are many other ways to make it, hope it helps!