)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

Point DIV at Another DIV (Angle Between Two Points)

  1. const dot = document.createElement('div')
  2. Object.assign(dot.style, {
  3.   position: 'absolute',
  4.   left: '100px', 
  5.   top: '100px',
  6.   width: '10px', 
  7.   height: '10px',
  8.   transform: 'translate(-5px, -5px)',
  9.   background: 'black'
  10. });
  11. document.body.appendChild(dot);
  12.  
  13. const pointer = document.createElement('div');
  14. Object.assign(pointer.style, {
  15.   position: 'absolute',
  16.   left: '-10px', 
  17.   top: '-5px',
  18.   width: '20px', 
  19.   height: '10px',
  20.   background: 'red'
  21. });
  22. document.body.appendChild(pointer);
  23.  
  24. // desktop only (`touchmove` needed for mobile)
  25. document.addEventListener('mousemove', (e) => {
  26.   const dx = parseFloat(dot.style.left) - e.clientX;
  27.   const dy = parseFloat(dot.style.top) - e.clientY;
  28.   const angle = Math.atan2(dy, dx) / Math.PI * 180;
  29.  
  30.   pointer.style.transform = `
  31.     translate(${e.clientX}px, ${e.clientY}px)
  32.     rotate(${angle}deg)
  33.   `;
  34. });

Moving your mouse around the page, you’ll notice the red div always points at the black div. (more…)

snippet.zone ~ 2021-24 /// {s/z}