見出し画像

#66 スマホでドラッグ&ドロップのUIを作りたい【ぴよぴよコーダーの開発日記】

ドラッグ&ドロップで何か作りたいなぁと思って、ラクにできるものはないか考えたら、昔jQueryUIでそんな機能があったなぁと思いだしたので実装してみました。

作りたいもの
簡単な英文法クイズ

コード

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>eigo</title>
  <link rel="stylesheet" href="./lib/jquery-ui.css">
  <style>
  #app {
    text-align: center;
  }
  [id^="draggable"] {
    display: inline-block;
    padding: 6px;
    line-height: 1.0;
    border: 1px solid #aaa;
  }
  
  #droppable {
    display: inline-block;
    width:10em;
    height: 1em;
    padding: 6px;
    line-height: 1.0;
    border: 1px solid #aaa;
  }
  </style>
  
</head>
<body>
<div id="app"> 
<p id="draggable">am</p>
 
<p id="draggable2">have</p>

<p>I <span id="droppable" class="ui-widget-header"></span> a pen.</p>
</div> 
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.3/jquery.ui.touch-punch.min.js"></script>
<script>
  $( function() {
    $( "#draggable" ).draggable({ revert: "valid" });
    $( "#draggable2" ).draggable({ revert: "invalid" });
 
    $( "#droppable" ).droppable({
      classes: {
        "ui-droppable-active": "ui-state-active",
        "ui-droppable-hover": "ui-state-hover"
      },
      drop: function( event, ui ) {
        $( this )
          .addClass( "ui-state-highlight" );
      }
    });
  } );
</script>
</body>
</html>

まずはヘッダーで下記のCSSを読み込む
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">

bodyの直前で下記のJSを読み込む
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.3/jquery.ui.touch-punch.min.js"></script>

上から、jquery、jqueryUI、jquery.ui.touch-punch。3つ目のjquery.ui.touch-punchを読み込まないとスマホで動きません。

HTMLは、これだけ
<p id="draggable">am</p>
<p id="draggable2">have</p>
<p>I <span id="droppable" class="ui-widget-header"></span> a pen.</p>

ドラッグする要素にdraggableなどとクラスを付ける
ドロップする要素にdroppableなどとクラスを付ける

JSはドラッグさせたい要素にrevert: invalidを指定。ドラッグさせたくない要素にはrevert:validを。

$( "#draggable" ).draggable({ revert: "valid" });
$( "#draggable2" ).draggable({ revert: "invalid" });

後はドロップする要素の実行とクラスの付け替えオプション

$( "#droppable" ).droppable({
      classes: {
        "ui-droppable-active": "ui-state-active",
        "ui-droppable-hover": "ui-state-hover"
      },
      drop: function( event, ui ) {
        $( this )
          .addClass( "ui-state-highlight" );
      }
});

デモ

<参考>

※ヘッダー画像は、ロートレックのレザンバサドゥールでのカフェコンサート At Les Ambassadeurs (Au Café-Concert / At the Café Concert)


この記事が気に入ったらサポートをしてみませんか?