Skip to content

can select multiple be draggable?

var drag = document.getElementById("drag");

drag.onclick = function(e){
  e.preventDefault();
}
#drag {
  width: 50px;
}
<select id="drag" multiple="">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

is it possible with javascript to stop the hold-select effect and make it a drag to change elements order in the list?

i tried to e.preventDefault() and to bind a draggable script in options but did not work

Answer

I don’t think you can do that with select element :

Trying to change the code you provide making a simple one

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>title</title>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>
  <body>
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
    </ul>
  </body>
</html>

script.js :

$("ul").on('click', 'li', function (e) {
    if (e.ctrlKey || e.metaKey) {
        $(this).toggleClass("selected");
    } else {
        $(this).addClass("selected").siblings().removeClass('selected');
    }
}).sortable({
    connectWith: "ul",
    delay: 150, 
    revert: 0,

});

However you can use multiselect plugin ,a demo here

EDITED :

If you still want the select tag look you can use dragOptions

$(document).ready(function(){
    $("#drag").dragOptions({
        onDrag: function(){
            console.log('onDrag callback: ', this);
        },
        onChange: function(){
            console.log('onChange callback: ', this);
        }
    });
});
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>drag</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
  </head>
  <body>
    <div class="form-group">
    <select id="drag" size="5" class="form-control">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
    </select>
    </div>
  </body>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://gitcdn.link/repo/NikitaKA/jquery.dragOptions/master/jquery.dragoptions.min.js" type="text/javascript" language="javascript"></script>
</html>

As you see when you drag an option an error occurs (maybe an issue))

If someone can tell me what’s going wrong here i will appreciate that !

Hope that helps someone .