0

After failing to get selenium to drag and drop an element, how can this be done using javascript?

Below is an example of elements that can be reordered using drag and drop, I need the drag and drop part to happen using a js function call and the items to be reordered accordingly.

    function listItemDragged(e) {
      e.target.classList.add("dragging");
      let dropTarget =
        document.elementFromPoint(e.clientX, e.clientY) === null
          ? e.target
          : document.elementFromPoint(e.clientX, e.clientY);

      if (e.target.parentNode === dropTarget.parentNode) {
        dropTarget =
          dropTarget !== e.target.nextSibling ? dropTarget : dropTarget.nextSibling;
        e.target.parentNode.insertBefore(e.target, dropTarget);
      }
    }

    function listItemDropped(e) {
      e.target.classList.remove("dragging");
      e.preventDefault();
    }

    function onLoad() {
      let listItems = document.querySelectorAll(".draggable");
      Array.prototype.map.call(listItems, (option) => {
        option.ondrag = listItemDragged;
        option.ondragend = listItemDropped;
      });
      document.querySelector('.sortable-list').addEventListener("dragover", (e) => e.preventDefault());
    }

    onLoad();
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-family: 'Roboto', sans-serif
    }

    body {
        background-color: #2b3035;
    }

    .draggable {
        display: flex;
        margin-top: 10px;
        padding: 10px 12px;
        border-radius: 5px;
        border: 1px solid #5c636a;
        margin-right: 5px;
        background-color: #212529;
        cursor: grab;
        color: #ffffff;
        touch-action: none
    }

    .dragging {
        cursor: grabbing;
        background: transparent;
        color: transparent;
        border: none;
    }
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" />

    <ul class='sortable-list list-unstyled'>
      <li class='draggable' draggable='true'>
        Lorem ipsum dolor sit amet 1
      </li>
      <li class='draggable' draggable='true'>
        Lorem ipsum dolor sit amet 2
      </li>
      <li class='draggable' draggable='true'>
        Lorem ipsum dolor sit amet 3
      </li>
      <li class='draggable' draggable='true'>
        Lorem ipsum dolor sit amet 4
      </li>
    </ul>

The solution suggested here uses jquery-ui which for some reason interferes with how the event handling defined above works and sends elements at the wrong coordinates. Is there a way to achieve the same thing using vanilla js?

nlblack323
  • 155
  • 1
  • 10

0 Answers0