DIV position within the cursor, but within the visible area

I am using the showDiv function below to display the DIV popup menu at the cursor position, but I cannot figure out how to set it up so that the menu does not disappear from the bottom or right edge of the visible area, can I compensate for this before showing the DIV?

var posx;
var posy; 

function getMouse(e){ 
 posx = 0;
 posy = 0; 
 if (!e) var e = window.event; 
 if (e.pageX || e.pageY){ 
  posx = e.pageX;
  posy = e.pageY; 
 } 
 else if (e.clientX || e.clientY){ 
  posx = e.clientX;
  posy = e.clientY; 
 } 
} 

function showDiv(id){ 
 var obj = document.getElementById(id); 
 obj.style.left=posx+'px'; 
 obj.style.top=posy+'px'; 
 obj.style.display='block';
}

...

<body onMouseMove="getMouse(event)">

      

+3


source to share


2 answers




function showDiv(id){ 
  var obj = document.getElementById(id),
    screenWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0) - (obj.clientWidth || obj.offsetWidth),
    screenHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0) - (obj.clientHeight || obj.offsetHeight);

  obj.style.left = Math.min(posx, screenWidth) + 'px'; 
  obj.style.top = Math.min(posy, screenHeight) + 'px'; 
  obj.style.display = 'block';
}
      

Run codeHide result


0


source


This should contain a div within the viewport.

You are just checking if the width is plus position, etc. more or less values ​​for the viewable area.



We also add left scrolling and scrolling to the top, so our calculations don't mistakenly think this is visible; you can remove this if you don't need it.

function showDiv(id, posX, posY) {
  var obj = document.getElementById(id),
      objWidth = obj.offsetWidth,
      objHeight = obj.offsetHeight,
      docX = window.pageXOffset || document.documentElement.scrollLeft,
      docY = window.pageYOffset || document.documentElement.scrollTop,
      winWidth = document.documentElement.clientWidth,
      winHeight = document.documentElement.clientHeight;

  posX += docX;
  posY += docY;

  if (posX < docX) {
    posX = docX;
  } else if (posX + objWidth > winWidth + docX) {
    posX = docX + (winWidth - objWidth);
  }

  if (posY < docY) {
    posY = docY;
  } else if (posY + objHeight > winHeight + docY) {
    posY = docY + (winHeight - objHeight);
  }

  obj.style.top = posY + 'px';
  obj.style.left = posX + 'px';
  obj.style.display = 'block';
}

      

0


source







All Articles