desandro / draggabilly

:point_down: Make that shiz draggable
https://draggabilly.desandro.com
MIT License
3.86k stars 387 forks source link

Programatically starting drag #89

Closed babysteps closed 8 years ago

babysteps commented 9 years ago

I am using draggabilly to move a volume slider, but also allow clicking on the container element to reposition the drag element. In the case that a user clicks on the container element, and I reposition the drag element, is there any way to start the dragging of the drag element programatically? I would like to start dragging on 'mousemove' over the container element while the mouse is down. I just need a way to start dragging other than a 'click' on the drag element.

Thanks again!

desandro commented 9 years ago

Have you tried using jQuery's .animate() with left or top? I believe this should work.

babysteps commented 8 years ago

Hello. I am still trying to figure this out. I think you may have misunderstood my question. I am just looking for a method that would start the draggabilly element dragging without having to be on the dragger element.

For example, my "container" width is 100px, and the dragger/handle is 10px wide and sitting at 50px from the left of the inside of the "container". A user mouses down 30px from the left of the "container". I would like to move the dragger/handle to this place, and start dragging.

Something like:

$( container ) .mousedown(function (e) { dragger.draggabilly('startDrag'); });

desandro commented 8 years ago

Could you put together a reduced test case? See https://github.com/desandro/draggabilly/blob/master/contributing.md#reduced-test-case-required

wa3l commented 8 years ago

In case someone else has the same problem as @babysteps, below is my solution. The idea is to intercept mousedown events on the container, move the drag element under the mouse and then programmatically start dragging:

var dragEl = document.getElementsByClassName('drag-element')[0];

// get a Draggabilly instance
var draggabilly = new Draggabilly(dragEl, {
    // options
});

$('.container').on('mousedown', function(e) {
    // register clicks anywhere on the container *except* the drag element
    if (e.target !== dragEl) {
        // move the drag element under the mouse pointer
        dragEl.style.left = e.offsetX;
        dragEl.style.top = e.offsetY;
        draggabilly.pointerDown(e, e); // start dragging
    }
});