0

I have a draggable div, inside it is a button, this button will popup a modal on clicked. But whenever i click on that div in order to drag it, it triggers the onclick event of the button as well. I want to disable that button if i were dragging, it should only be trigger when i simply click on it.

dragElement(document.getElementById("fdivAdd"));

function dragElement(elmnt) {
  var pos1 = 0,
    pos2 = 0,
    pos3 = 0,
    pos4 = 0;
  if (document.getElementById(elmnt.id + "header")) {
    /* if present, the header is where you move the DIV from:*/
    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
  } else {
    /* otherwise, move the DIV from anywhere inside the DIV:*/
    elmnt.onmousedown = dragMouseDown;
  }

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }

  function closeDragElement() {
    /* stop moving when mouse button is released:*/
    document.onmouseup = null;
    document.onmousemove = null;
  }
}
#fdivAdd {
  width: 80px;
  height: 80px;
  position: fixed;
  right: 45px;
  bottom: 93px;
  cursor: pointer;
  z-index: 9;
  background-color: #007bff;
  border-radius: 40px;
}

#fbtnAdd {
  width: 80px;
  height: 80px;
  border-radius: 40px;
  /* margin: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  -ms-transform: translateY(-50%) translateX(-50%);
  transform: translateY(-50%) translateX(-50%); */
  font-size: 25px;
  color: white;
}
<div id="fdivAdd">
  <p id="fbtnAdd" data-toggle="modal" data-target="#exampleModal" data-whatever="@getbootstrap">Add</p>
</div>

1 Answer 1

0

Use a boolean and make life easy:

var moving = false;
if(moving == true) {
   disableBtn("Button Id");
} else {
  // Do what you did before
}

function disbaleBtn(btnId) {
  console.log(btnId);
  document.getElementById(btnId).onclick = "return false";
}

Set the bool to true in your dragging code, and false while not. Add the if statement to where the onclick is otherwise used

2
  • in my code above,which part is being used for dragging? i've copied it on W3Schools so i don't clearly understand it Commented Oct 25, 2020 at 18:28
  • In dragelement function Commented Oct 25, 2020 at 19:44

Not the answer you're looking for? Browse other questions tagged or ask your own question.