Drag and drop only works with two clicks

Asked

Viewed 80 times

0

I’m having trouble "dragging and dropping" the items on my list. I can only hold and drag an item after a single click on it. Does anyone know how I solve this ? Follow my code:

<ul id="sortable">
<li>
    <a>
    <span class='item' style='cursor: pointer;' onmouseup='atualizaposicao(this.id);' id='1'>Maçã</span>
    </a>
</li>
<li>
    <a>
    <span class='item' style='cursor: pointer;' onmouseup='atualizaposicao(this.id);' id='2'>Biribinha</span>
    </a>
</li>
<li>
    <a>
    <span class='item' style='cursor: pointer;' onmouseup='atualizaposicao(this.id);' id='3'>Astronauta</span>
    </a>
</li>

function atualizaposicao(id) {
    var id;
    $("#sortable").sortable({
        start: function(event, ui) {
            ui.item.startPos = ui.item.index();
        },
        update: function(event, ui){

            console.log("Posição inicial: " + ui.item.startPos + " Nova posição: " + ui.item.index());

            var itens = $(this).children();
            console.log("Quantidade de itens: " + itens.length);

            itens.each(function(){
                var item = $(this).children();

                var newVal = $(this).index() + 1;
                $(item).children('.index').html(newVal);

            });

            console.log("***********************************");

            var jqxhr = $.ajax({
                url: "/aleatoriedades.php",
                type: "POST",
                data: {
                    timeout: default_timeout,
                    id: id,
                    acao: "salvar_ordem",
                    novaposicao: ui.item.index(),
                    seed: random()
                }
            })
                    .done(function () {

                    })
                    .fail(function (jqXHR, textStatus) {
                        if (textStatus == 'timeout') {
                            swal("Tempo Esgotado", "Verifique sua conexão e tente novamente em alguns segundos.", "error")
                            return;
                        }
                        swal("Erro", "Ocorreu um erro de comunicação. Verifique sua conexão.", "error")
                    });
        }
     });
    $("#sortable").disableSelection();
}
  • Hello, do not put the solution in the body of the question, can pose as an answer to your own question meanwhile ;)

1 answer

2

I did a quick test and it seems to me that your problem is to call the update function with the event Mouseup, you are running the whole function when the mouse is released (several times, not starting automatically, it is necessary to click on a list item before sortable works).

To solve this problem I changed a little the code of the update function, basically moved the ajax part to a function change stop inside sortable.

  • The event change is called every time an item changes position;
  • The event update is called when user stops moving or some item has changed position;
  • The event stop is called when the user stops moving (releases the item).

For a complete list of events, click here (https://api.jqueryui.com/sortable/).

I also modified the place where the ID was set in HTML for the li instead of span, just because it’s easier to get the ID that way and it’s easier to understand/read.

And finally call the update function when the window is loaded (add to the body tag a onload="atualizaposicao();") or do otherwise.

JS:

function atualizaposicao() { //Não precisa passar o ID
    $("#sortable").sortable({
        start: function(event, ui) {
            ui.item.startPos = ui.item.index();
        },
        stop: function( event, ui ) {
            console.log("Posição inicial: " + ui.item.startPos + " Nova posição: " + ui.item.index());

            var itens = $(this).children();
            console.log("Quantidade de itens: " + itens.length);

            itens.each(function(){
                var item = $(this).children();

                var newVal = $(this).index() + 1;
                $(item).children('.index').html(newVal);

            });


            var id = $(ui.item).attr("id"); //Pega o ID do item que mudou de posição

            var jqxhr = $.ajax({
                url: "/aleatoriedades.php",
                type: "POST",
                data: {
                    timeout: default_timeout,
                    id: id,
                    acao: "salvar_ordem",
                    novaposicao: ui.item.index(),
                    seed: random()
                }
            }).done(function () {
                //Codigo aqui...
            }).fail(function (jqXHR, textStatus) {
                //Codigo de falha.
            }
     )}});
    $("#sortable").disableSelection();
}

atualizaposicao(); //Remova essa linha se estiver chamando a função com onload.

HTML:

<ul id="sortable">
  <li  id='1'>
      <a href="#">
        <span class='item' style='cursor: pointer;'>Maçã</span>
      </a>
  </li>
  <li  id='2'>
      <a href="#">
        <span class='item' style='cursor: pointer;'>Biribinha</span>
      </a>
  </li>
  <li id='3'>
      <a href="#">
        <span class='item' style='cursor: pointer;' >Astronauta</span>
      </a>
  </li>
</ul>
  • It needs to be in the mouseup, because I want you to save when I release the element. The way you suggested the page keeps saving every click I give in the element. And the function is not bringing the new position.

  • Change change to stop (I confused the 2 when I wrote the answer, change is called when the elements change position, stop is called when the Sort is finished). Also move the Update code to the stop function. I will update the response.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.