Ian
Ian

Reputation: 6124

jQuery enable and disable drag and drop selection

I am trying to use threedubmedia's drag and drop selection capability as shown in the demo here. I have all that code figured out, but what I can't figure out is how to enable and disable the functionality. I assume this uses bind() and unbind(), but I've never used those before and can't figure out how it would work. Basically, I want to be able to click a button to enable it and another to disable it. How do I do this?

Upvotes: 0

Views: 1646

Answers (1)

Joe
Joe

Reputation: 2105

here is a fiddle of that example demo copied and working with added unbind and re-bind functionality.

.unbind() should be called on the element you wish to remove bindings from, in this particular case the $(document) element is our target. without any parameters .unbind() will remove all bindings from that element, but you can also pass it specific event parameters to just remove those.

what i have done in the above fiddle is add a click function on the unbind button to remove the bindings for the document element and a second click function for the rebind button to re attach them. ive added some basic html and css to go along with additional jquery to perform the unbinding / re-binding

HTML

<div class="unbind">UNBIND the drag drop Document Handlers</div>
<div class="rebind">RE-BIND</div>

CSS

.unbind{
    display:block;
    padding:10px 30px;
    background: red;
    cursor:pointer;
    position:absolute;
    bottom: 100px;
    color: white;
    font-family: Arial;
    font-size:25px;
}

.rebind{
    display:block;
    padding:10px 30px;
    background: green;
    cursor:pointer;
    position:absolute;
    bottom: 10px;
    color: white;
    font-family: Arial;
    font-size:25px;
}

JS

$('.unbind').click(function(){
     alert("unbound");
     $(document).unbind();
});
$('.rebind').click(function(){
     alert("rebound");
        $( document )
        .drag("start",function( ev, dd ){
            return $('<div class="selection" />')
                .css('opacity', .65 )
                .appendTo( document.body );
        })
        .drag(function( ev, dd ){
            $( dd.proxy ).css({
                top: Math.min( ev.pageY, dd.startY ),
                left: Math.min( ev.pageX, dd.startX ),
                height: Math.abs( ev.pageY - dd.startY ),
                width: Math.abs( ev.pageX - dd.startX )
            });
        })
        .drag("end",function( ev, dd ){
            $( dd.proxy ).remove();
        });
});    

enjoy

Upvotes: 1

Related Questions