Home > OS >  Fix draggable position in multiple div
Fix draggable position in multiple div

Time:06-25

in my code i want divs and draggables elements dynamically, my problem is that the draggable elements are moving along the bottom of the div when scrolling, and I need that when I drag them over the div they don't move when scrolling the page.

The code jsFiddle

  $(".signatureImage").on("mousedown mouseup", function(e) {

    }).draggable({
      containment: ".documents",
      cursor: "all-scroll",
      scroll: false, 
      //helper: "clone",
      grid: [5, 5],
      zIndex: 1000,
      drag: function(event,ui){
        var offset = $(this).offset();
        var xPos = offset.left;
        var yPos = offset.top;
      },
        stop: function(e, ui) {

          var finalxPos = ui.position.left;
          var finalyPos = ui.position.top;

          console.log('Stop: ' finalxPos   ' - ' finalyPos);
          jQuery.post("ajaxs/",
          {

            finalxPos:  finalxPos,
            finalyPos:  finalyPos,
          }, function(data)
          {});
        }
    }).each(function(i, item){    
    });

Drag the element inside the div and then use the scroll of the containerDocuments div, you will see that the draggable elements are moving along with the scroll

CodePudding user response:

Consider the following example.

Fiddle: https://jsfiddle.net/Twisty/n5yrtou1/16/

JavaScript

$(function() {
  $(".signatureImage").draggable({
    containment: ".documents",
    cursor: "all-scroll",
    scroll: false,
    grid: [5, 5],
    zIndex: 1000,
    stop: function(e, ui) {
      var finalxPos = ui.position.left;
      var finalyPos = ui.position.top;
      console.log('Stop: '   finalxPos   ' - '   finalyPos);
    }
  });

  $("#containerDocuments").droppable({
    drop: function(e, ui) {
      var el = ui.helper.detach();
      el.css({
        top: "",
        left: "",
        position: "absolute",
        "z-index": 1000
      }).appendTo(this).position({
        my: "center",
        at: "center",
        of: e
      });
    }
  });
});

Using Droppable, you can detach the Draggable element and attach it to your DIV. It is then a matter of positioning it. You can do this in many different ways, yet I opted to base it on the Event.

Initially, with your code, when you dragged it and stopped, it was given a Top & Left position based on the relative position to it's parent. When you drop it, the new position has to be relative to the new target element. You can do this with .offset(), yet it's complicated.

This allows the user to drag an element from the right onto the images, it attaches, and now when the user scrolls, the image scrolls with the rest of the DIV.

See More:

  • Related