jQuery: Detect dragging, and adding temporary a specific style

I work with this, and realized that links always get fired if you drag them. I would like to avoid that, and coded this:

$("div").drag(function() {
  alert("Link should not be clickable while dragging.");
  $("div a").css("pointer-events", "none");
});
div {
  padding: 10px;
  background-color: yellow;
  display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div><a href="https://www.wikipedia.org/">Wikipedia</a></div>

Unfortunately, the .drag(function() { does not exist. Is there another way to code it like that?

And yes, I have already read this article. I have tried all what is written there, but was not able to fix it.

Would be very thankful for help! <3

Answer

this could be a solution, the idea is to capture the event and prevent it if there was a pointer movement:

// solution
(() => {
  let lock = 0;
  const prevent = e => {
    if (lock !== 2)
        return;
    e.preventDefault();
    e.stopPropagation();
  };
  const unlock = e => {
    prevent(e);
    setTimeout(() => lock = 0);
  };
  mydiv.addEventListener('click', prevent, true);
  mydiv.addEventListener('pointerdown', e => lock = 1, true);
  mydiv.addEventListener('pointermove', e => lock && (lock = 2), true);
  mydiv.addEventListener('pointerup', unlock, true);
  mydiv.addEventListener('pointercancel', unlock, true);
})();
#mydiv {
  position: absolute;
  z-index: 9;
  background-color: #f1f1f1;
  text-align: center;
  border: 1px solid #d3d3d3;
}

#mydivheader {
  padding: 10px;
  cursor: move;
  z-index: 10;
  background-color: #2196F3;
  color: #fff;
}
some random drag example
<div id="mydiv">
  <a href="https://www.wikipedia.org/">Wikipedia</a>
  <p>Move</p>
  <p>this</p>
  <p>DIV</p>
</div>

<script>
dragElement(document.getElementById("mydiv"));
function dragElement(elmnt) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  if (document.getElementById(elmnt.id + "header")) {
    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
  } else {
    elmnt.onmousedown = dragMouseDown;
  }
  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    document.onmousemove = elementDrag;
  }
  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }
  function closeDragElement() {
    document.onmouseup = null;
    document.onmousemove = null;
  }
}
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *