MyDaftQuestions
MyDaftQuestions

Reputation: 4691

How to trigger dragend event

How do I force a dragend event to fire? I use a library that automatically adds a listener to elements which looks for a long press (for touch screen to simulate a right click event). I don't want that to fire when a user tries to drag (but the nature of dragging means, they click and hold/long press)

I know how to set one up, but what I'd like is

instrumentInfo.addEventListener("dragstart", function (e) {
    e.preventDefault();//stop longpress working for touch screens
    e.dragend(); //not going to work
    instrumentInfo.dispatchEvent("dragend");//does not work
    instrumentInfo.dispatchEvent(new Event("dragend"));//no exception but does not seem to work
}

I understand I may get race conditions and am OK with that

Upvotes: 1

Views: 924

Answers (2)

KemalTuzer
KemalTuzer

Reputation: 1

All events you need are 'mousemove/down/up'. Espacially, mousemove is important! You can imitate any event like 'select, drag, dragstart/end' with the three.

let timeout = null;
const div = document.querySelector('.textarea');
div.focus();
let isDragging = false;
div.onmousedown = () => {
  isDragging = true;
  div.addEventListener('mousemove', handleSomething)
}
div.parentElement.onmouseup = () => {
  clearTimeout(timeout);
  isDragging = false;
  timeout = setTimeout(() => div.removeEventListener('mousemove', handleSomething), 0);
} 
div.ondblclick = () => {
  handleSomething(true);
}

function handleSomething (ignoreIsDragging = false) {
  const { anchorOffset: start, focusOffset: end, focusNode, isCollapsed } = document.getSelection();
  const { data } = focusNode;
  const parsed = data ? data?.slice(end, start)?.trim() || data.slice(start, end)?.trim() : null;
  if( !isCollapsed && (isDragging || ignoreIsDragging))
    console.log(parsed);
}
.container{
  width: 100vw;
  height: 100vh;
  display: grid;
  place-content: center;
}
.textarea{
  width: 90vw;
  height: 90vh;

  background: #eee;
}
<div class="container">
  <div contenteditable="true" class="textarea"></div>
</div>

Upvotes: 0

MyDaftQuestions
MyDaftQuestions

Reputation: 4691

And the answer is, execute the mouseup event

instrumentInfo.dispatchEvent(new Event("mouseup"));

Upvotes: 1

Related Questions