Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to drop an element on mouseup event

Here is the jQuery code that I have written to drag multiple items at a time. It is draggable now but not droppable.

here is the code

    $(document).on('click', function (e) {
        var target = e.target;
        if (!$(target).hasClass('a')) $('.selected').removeClass('selected');
    });
    $(document).delegate('.a', 'dblclick', function (e) {
        $(this).addClass('selected');
    });

    $(document).delegate('.selected', 'mousedown', function (e) {
        var div = $('<div></div>');
        $('.selected').each(function () {
            div.append($(this).clone());
        });
        div.prop('id', 'currentDrag');
        $('#currentDrag').css({
            left: e.pageX + "px",
            top: e.pageY + "px"
        });
        $('body').append(div);
    });

    $(document).on('mouseup', function (e) {
        var tgt = e.target;
        var mPos = {
            x: e.pageX,
            y: e.pageY
        };
        $('.drop').each(function () {
            var pos = $(this).offset(),
                twt = $(this).width(),
                tht = $(this).height();
        });
        if((mPos.x > pos.left) && (mPos.x < (pos.left + twt)) && (mPos.y > targPos.top) && (mPos.y < (pos.top + tht))) {
            $(this).append($('#currentDrag').html());
        }
        $('.drop .selected').removeClass('selected');
        $('#currentDrag').remove();
    });
    $('.drop').on('mouseup', function (e) {
        $(tgt).append($('#currentDrag').html());
        $('.drop .selected').removeClass('selected');
        $('#currentDrag').remove();
    });

    $(document).on('mousemove', function (e) {
        $('#currentDrag').css({
            left: e.pageX + "px",
            top: e.pageY + "px"
        });
    });

What is the pronblem with my code and how can I achieve this. here is the fiddle http://jsfiddle.net/mDewr/27/

like image 696
Exception Avatar asked Sep 14 '13 06:09

Exception


People also ask

How do I get rid of mouseup event?

Almost always, mouseup and click can be used synonymously. In order to cancel the click , like you demonstrated, you can return false in the mousedown event callback which prevents the click event from ever completing.

Does mouseup fire before click?

Mouseup is always firing before click, despite this order.

What is mouseup event in JavaScript?

The mouseup event is fired at an Element when a button on a pointing device (such as a mouse or trackpad) is released while the pointer is located inside it. mouseup events are the counterpoint to mousedown events.

How do I trigger a mouseup event?

The mouseup event occurs when the left mouse button is released over the selected element. The mouseup() method triggers the mouseup event, or attaches a function to run when a mouseup event occurs. Tip: This method is often used together with the mousedown() method.


3 Answers

I would really recommend trying to find a way to make the jQuery UI draggable and droppable libraries work for you. Then the question becomes, similar to this one: How do I drag multiple elements with JavaScript or jQuery?.

Here's how we can apply one of the answers from that question to your problem. I'm using the jQuery UI multiple draggable plugin, the entire script of which can be found here: jquery.ui.multidraggable-1.8.8.js.

First let's simplify your HTML. By putting our draggable and dropable divs inside of elements, we don't have to apply redundant stylings to each one. Instead we can use the containing element to style

HTML

<div id="parent">
    <div id="dragTargets">
        <div>123</div>
        <div>456</div>
        <div>789</div>
    </div>
    <div id='dropTargets'>
        <div></div>
        <div></div>
    </div>
</div>

Using the plugin we can call multidraggable on each of the drag divs. And droppable anywhere they can be dropped

JavaScript

$("#dragTargets div").multidraggable();
$("#dropTargets div").droppable();

Customize

We can control the appearance with styling. As an example, we'll make anything that can receive drops yellow, anything you're about to drop as red, and anything that has received an element green.

Here's some styling as an example in CSS

.ui-state-highlight { background: green; }
.ui-state-active { background: yellow; }
.ui-state-hover { background: red; }

And we'll control when these classes are applied with JavaScript:

$("#dropTargets div").droppable({
    activeClass: "ui-state-active",
    hoverClass: "ui-state-hover",
    drop: function () {
        $(this).addClass("ui-state-highlight")
    }
});

Multi-Draggable

You should style the elements that are currently selected. The script will apply the class ui-multidraggable to all the currently selected elements. The following CSS will make it apparent to the user that their choice is selected.

.ui-multidraggable {
    background: tan;
}

Check out this demo. Just hold down ctrl to select more than one of the divs and then drag all of them at once.

jsFiddle

like image 123
KyleMit Avatar answered Oct 17 '22 03:10

KyleMit


There are few errors in you code. You can check errors on browser console.
To check elements over droppable area, you should check the drop area in the each loop, rather than after each loop. When moving mouse, you should better turn off selection to avoid selected text flashing

$(document).on('click', '.a', function (e) {
   $(this).removeClass('selected');
});
$(document).on('dblclick', '.a', function (e) {
    $(this).toggleClass('selected');
});
$(document).on('mousedown', '.selected', function (e) {
    var dragMode = true;
    var div = $('<div></div>');
    $('.selected').each(function () {
        div.append($(this).clone());
    });
    div.prop('id', 'currentDrag');
    $('#currentDrag').css({
        left: e.pageX + "px",
        top: e.pageY + "px"
    });
    $('body').append(div);
    //disable selection on dropping start
    disableSelection();
    $(document).on('mousemove.drop', function(e){
       onDragging(e, dragMode);
    });
    $(document).on('mouseup.drop', function(e){
       onDragEnd(e, dragMode);
    });
});
function onDragEnd(e, dragMode){
    if(!dragMode)
       return;
    var tgt = e.target;
    var mPos = {
        x: e.pageX,
        y: e.pageY
    };
    $('.drop').each(function () {
        var pos = $(this).position(),
            twt = $(this).width(),
            tht = $(this).height();
         if((mPos.x > pos.left) && 
            (mPos.x < (pos.left + twt)) && 
            (mPos.y > pos.top) && 
            (mPos.y < (pos.top + tht))) {
            $(this).append($('#currentDrag').html());
        }
    });

    $('.drop .selected').removeClass('selected');
    $('#currentDrag').remove();
    $('.onDrop').removeClass('onDrop');
    //remove listener on docuemnt when drop end
    $(document).off('mousemove.drop');
    $(document).off('mouseup.drop');
    //enable selection
    enableSelection();
}    
function onDragging(e, dragMode){
    if(!dragMode)
       return;
    var p = $('body').offset();
    var mPos = {
        x: e.pageX,
        y: e.pageY
    }; 
    $('#currentDrag').css({
        left: mPos.x,
        top: mPos.y
    });
     $('.drop').each(function () {
        var pos = $(this).position(),
            twt = $(this).width(),
            tht = $(this).height();
         $(this).toggleClass("onDrop",
              (mPos.x > pos.left) 
                 && (mPos.x < (pos.left + twt)) 
                 && (mPos.y > pos.top) 
                 && (mPos.y < (pos.top + tht)) 
        );  
    });
}
function disableSelection(){
    $(document).on("selectstart", function(){   return false; });
    //firefox
    $("body").css("-moz-user-select", "none");
}  
function enableSelection(){
    $(document).off("selectstart");
    //firefox
    $("body").css("-moz-user-select", "");
}  

I updated your code: http://jsfiddle.net/mDewr/46/, may can help you.

like image 45
iamght Avatar answered Oct 17 '22 01:10

iamght


There were several errors, which I'll not list now, but you can compare the old version with the new one.

    $(document).on('dblclick', '.a', function (e) {
      $(this).toggleClass('selected');
    });

    $(document).on('mousedown', '.selected', function (e) {
      var div = $('<div id="currentDrag"></div>');
      $('.selected').each(function () {
          div.append($(this).clone(true));
      });
      var p = $('body').offset();
      var l = e.pageX - p.left;
      var t = e.pageY - p.top;
      console.log(l, ', ', t);
      $('body').append(div);
      $('#currentDrag').css({
          left: l,
          top: t
      });

    });

    $(document).on('mouseup', '.selected', function (e) {
      $('.d').each(function(index, item){
          var $i = $(item);
          if (e.pageX >= $i.offset().left &&
              e.pageX <= $i.offset().left + $i.width() &&
              e.pageY >= $i.offset().top &&
              e.pageY <= $i.offset().top + $i.height()) {       
              console.log('Dropped');
              var $cl = $('#currentDrag').find('>*').clone(true);
              $i.append($cl);
          }
      });
      $('.selected').removeClass('selected');          
      $('#currentDrag').remove();
    });

    $(document).on('mousemove', function (e) {    
      var p = $('body').offset();
      $('#currentDrag').css({
          left: e.pageX - p.left,
          top: e.pageY - p.top
      });          
    });

http://jsfiddle.net/mDewr/43/

Everything should work perfectly in this version (this is an update). PS: I've changed to 1.7+ jQuery, but you can easily change it back to <1.7. Also you don't need custom attributes, use css classes instead.

like image 38
Balint Bako Avatar answered Oct 17 '22 01:10

Balint Bako