How to manage scroll offset when allowing user to pin a div position in place?

Viewed 46

Attempting to allow users to pin a div in place by providing a button toggling that div's absolute/fixed positioning. If the user scrolls however, the pin position gets offset and moves when unpinned and pinned again. It seems to be a predictable pattern, but I have not been able to pick up on exactly what is going on. How can this be corrected?

From what I understand, absolute / fixed positioning are calculated relative to different positions (document / window). I am guessing that converting one position to the other based on scroll offset is needed?

function pin() {
  let container = document.getElementById('container');
  let draggablePos = container.getBoundingClientRect();
  container.classList.toggle('positionAbsolute'); // default on
  container.classList.toggle('positionFixed'); // default off
  container.style.top = draggablePos.y +  window.scrollY + 'px';
document.getElementById("pinbutton").innerText = document.getElementById("pinbutton").innerText == "PIN" ? "UNPIN" : "PIN";
}


/* The rest of the js is just here for the demo to run */

//Make the DIV element draggagle:
dragElement(document.getElementById("container"));

function dragElement(elmnt) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  document.getElementById("clicktarget").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;
  }
}
body {
  height: 3000px;
  background-color: #ccc;
  opacity: 0.8;
  background: repeating-linear-gradient( -45deg, #333, #444 5px, #333 5px, #333 25px );
}

.positionAbsolute {
  position: absolute;
}

.positionFixed {
  position: fixed;
}

#container {
  z-index: 9;
  background-color: red;
  text-align: center;
  border: 2px solid; 
  width: 300px;
  resize: vertical;
  overflow: auto;
}

#clicktarget {
  height: 100%;
  width: 100%;
  background: cyan;
  user-select: none;  
  cursor: move;
  min-height: 100px;
}
<div id="container" class="positionAbsolute">
  <div id="clicktarget">
    Click here to move
    <button id="pinbutton" onclick="pin();">PIN</button>
  </div> 
</div>

Codepen link

0 Answers
Related