Mr Abi Mr Abi - 6 months ago 14
Javascript Question

trigger drag and drop event by attributes

How can I track drag and drop event if I have more elements, like I have 4 div

<div data-val="val-1">Menu 1</div>
<div data-val="val-2">Menu 2</div>
<div data-val="val-3">Menu 3</div>
<div data-val="val-4">Menu 4</div>


and I have 8 list items

<ul>
<li id="something-1">Something 1</li>
<li id="something-2">Something 2</li>
<li id="something-3">Something 3</li>
<li id="something-4">Something 4</li>
<li id="something-5">Something 5</li>
<li id="something-6">Something 6</li>
<li id="something-7">Something 7</li>
<li id="something-8">Something 8</li>
</ul>


If I drag
li
having Id
something-3
into div having
data-val="val-2"
, How can post it to a file that should post both values.

Answer

Using the jquery UI function sortable and some ajax :

Javascript

$(function() {
  $( "ul" ).sortable({
    connectWith: ".connected",
    receive: function(event, elem) {
        var menu = $(this).data('val');
        var item = $(elem.item[0]).attr('id');
        $.post('yourphp.php', { item: item, menu: menu }, function () {
        console.log('Menu configuration saved !');
        });
    }
  }).disableSelection();
});

HTML

<h1>Menu 1</h1>
<ul class="connected" data-val="menu-1">
    <li id="something-1">Something 1</li>
    <li id="something-2">Something 2</li>
    <li id="something-3">Something 3</li>
    <li id="something-4">Something 4</li>
    <li id="something-5">Something 5</li>
</ul>
<h1>Menu 2</h1>
<ul class="connected" data-val="menu-2">
    <li id="something-6">Something 6</li>
    <li id="something-7">Something 7</li>
</ul>
<h1>Menu 3</h1>
<ul class="connected" data-val="menu-3">
    <li id="something-8">Something 8</li>
</ul>

JSFiddle