Stark
Stark

Reputation: 593

How to stop div from moving up when using mousemove?

I'm trying to keep the box from being dragged up, but can be dragged down, this is what I came up with but I can't figure out how to keep the original position so I have a reference to add it to the if check. It only appears after you scroll the main body a bit.

jsfiddle

window.addEventListener("scroll",function(){
  if($(document).scrollTop() > 100){
    $( ".box" ).slideDown({
      start: function () {
        $(this).css({
          display: "flex"
        })
      }
    });    
  }

  var top = 0;
  var divOverlay = document.getElementsByClassName('box')[0];
  var is_clicked = false;

  divOverlay.addEventListener('mousedown', function(e){   
    is_clicked = true;
    top = divOverlay.offsetTop - e.clientY
  }, true);

  document.addEventListener('mouseup', function(){
    is_clicked = false;
  }, true);

  document.addEventListener('mousemove', function(e){  
    event.preventDefault();

    // add a check here so it doesn't allow dragging the container up?
    if(is_clicked){
      divOverlay.style.top  = (e.clientY + top) + 'px';

      // if the box reaches 50px down, it should automatically hide it if the user
      //$('.box').slideUp();
    }
  }, true);

})

Upvotes: 0

Views: 143

Answers (1)

pl61
pl61

Reputation: 63

You could try using Math.max to limit the maximum top position of the box to viewport height minus box height:

document.addEventListener('mousemove', function(e){
  event.preventDefault();

  // add a check here so it doesn't allow dragging the container up?
  var maxTop = window.innerHeight - divOverlay.offsetHeight;
  if(is_clicked){
    divOverlay.style.top  = Math.max(maxTop, e.clientY + top) + 'px';

    // if the box reaches 50px down, it should automatically hide it if the user
    //$('.box').slideUp();
  }
}, true);

Upvotes: 1

Related Questions