JQuery UI drag and drop using live

this is a draggable sortable example on jqueryui website, i need to use live () with this (i think) because the elements are created using ajax, does anyone know how to apply a live event to the next?

<script>
    $(function() {
        $( "#sortable" ).sortable({
            revert: true
        });
        $( "#draggable" ).draggable({
            connectToSortable: "#sortable",
            helper: "clone",
            revert: "invalid"
        });
        $( "ul, li" ).disableSelection();
    });
    </script>
+3
source share
3 answers

You do not need to use liveit (and I don’t think you can), just plug them in as soon as you add them in the handler success. For example, when using load:

$("#target").load("your url", function() {
  // Replace the selectors below to match what you load
  $( "#target *[data-name=sortable]" ).sortable({
      revert: true
  });
  $( "#target *[data-name=draggable]" ).draggable({
      connectToSortable: "#target *[data-name=sortable]",
      helper: "clone",
      revert: "invalid"
  });
  $(this).find( "ul, li" ).disableSelection();
});

Living example

HTML- jQuery UI ( id data-name, ):

<ul>
  <li data-name='draggable' class="ui-state-highlight">Drag me down</li>
</ul>

<ul data-name="sortable">
  <li class="ui-state-default">Item 1</li>
  <li class="ui-state-default">Item 2</li>
  <li class="ui-state-default">Item 3</li>
  <li class="ui-state-default">Item 4</li>
  <li class="ui-state-default">Item 5</li>
</ul>
+2

, . , , - .

- :

// Call to add a new element
$.ajax({
  url: 'addElem',
  success: function(data) {
    $( "#newDraggableObject" ).draggable({
        connectToSortable: "#sortable",
        helper: "clone",
        revert: "invalid"
    });
  }
});
+2

, , , JQuery:

//Add draggable feature:
//Define a setup method for the draggable config so we can reuse it for dynamic elements
$(function() {
    jQuery.fn.draggableSetup = function draggableSetup() {
        this.draggable(
        {
            // enter your custom draggable code here...
        });
        return this;
    }
});

//Apply the draggable config your dynamic elements after adding them
$("#dynamic_element_id").draggableSetup();

.

, ajax .

+2

Source: https://habr.com/ru/post/1781399/


All Articles