0

I created a draggable Web-Component with a slot:

const DragItemTemplate = document.createElement("template");
DragItemTemplate.innerHTML =
  `<style>` +
    `div{` +
      `background: gray;` +
      `width: 200px;` +
      `height: 50px;` +
      `padding: 5px;` +
      `margin: 5px;` +
      `cursor: move;` +
      `display: flex;` +
      `align-items: center;` +
      `justify-content: center;` +
    `}` +
  `</style>` +
  `<div draggable="true">` +
    `<slot></slot>` +
  `</div>`;

class DragItem extends HTMLElement {
  constructor() {
    super();

    this.attachShadow({mode: "open"});
    this.shadowRoot.appendChild(DragItemTemplate.content.cloneNode(true));
  }
}

window.customElements.define("drag-item", DragItem);
<!DOCTYPE html>
<html lang="en">

<body>
  <drag-item></drag-item>
  <drag-item>Slotted Text</drag-item>
</body>

</html>

When I start dragging the component by clicking into the component (not the text) everything works as it should. But when I try to drag it by clicking on the text (slot) it doesn't work.

What could I do to make the whole component (including the text) draggable?

Ich
  • 65
  • 6
  • Does this answer your question? [Allow select text on a HTML 5 draggable child element](https://stackoverflow.com/questions/44855232/allow-select-text-on-a-html-5-draggable-child-element) – TwistedOwl Dec 06 '22 at 17:30
  • @TwistedOwl Unfortunately no. I don't want to select the text, but to be able to drag and drop my component no matter where I begin to drag it (by dragging it by the div itself `and the text`). – Ich Dec 06 '22 at 18:25

1 Answers1

1

Set slot { pointer-events:none } so nothing in the <slot> triggers a mouse event, and thus your <div draggable captures the drag

<drag-item></drag-item>
<drag-item>Slotted Text</drag-item>
<drag-item><div>Slotted Text</div></drag-item>

<script>
customElements.define("drag-item", class extends HTMLElement {
  constructor() {
    super()
      .attachShadow({mode:"open"})
      .innerHTML =
      `<style>` +
      `div{` +
        `background: gray;` +
        `width: 200px;` +
        `height: 50px;` +
        `padding: 5px;` +
        `margin: 5px;` +
        `cursor: move;` +
        `display: flex;` +
        `align-items: center;` +
        `justify-content: center;` +
      `}` +
      `slot{pointer-events:none}` + // <---------------
      `</style>` +
      `<div draggable="true">` +
        `<slot></slot>` +
      `</div>`;
  }
});
</script>
Danny '365CSI' Engelman
  • 16,526
  • 2
  • 32
  • 49