Help us understand the problem. What is going on with this article?

スマホ対応の超軽量VanillaなJavaScriptドラッグ&ドロップ

More than 3 years have passed since last update.

HTML5の標準でDrag&Dropが実装されましたので、jQueryなどを使わなくてもドラッグ&ドロップが簡単に実現できるようになりました。
しかしマウスイベントのみという状況なので、iPhoneなどのマウスを使わない、TouchイベントのデバイスではjQueryに頼っているという人も多いと思います。

jQueryやプラグインを使用しなくても、以下の様なVanillaの簡単なコードでリストの並び替えができます。

HTMLコード
<ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
</ul>
JavaScriptコード
var lis = document.querySelectorAll('li');
var draggingItem;
[].forEach.call(lis, function(li){
    li.setAttribute('draggable', true);
    li.addEventListener('touchstart', function(e){
        draggingItem = li;
    });
    li.addEventListener('touchend', function(e){
        draggingItem = null;
    });
    li.addEventListener('touchmove', function(e){
        e.preventDefault();
        var getOrder = function(elem){
            return [].indexOf.call(elem.parentNode.children, elem);
        }
        var pointedElement = document.elementFromPoint(e.pageX - window.pageXOffset, e.pageY - window.pageYOffset);
        if(!pointedElement.getAttribute('draggable') || pointedElement == draggingItem) return;
        var order = getOrder(pointedElement) - getOrder(draggingItem);
        if(order > 0) {
            pointedElement.parentNode.insertBefore(pointedElement, draggingItem);
        } else if (order < 0) {
            pointedElement.parentNode.insertBefore(draggingItem, pointedElement);
        }
    });
});

実際に動くデモは以下に置いています。
デモ

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした