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

Animate to Target

  1. function box(x, y, col = 'red', cursor){
  2.   const box = document.body.appendChild(
  3.     document.createElement`div`
  4.   )
  5.   box.classList.add(col + '-box')
  6.   Object.assign(box.style, {
  7.     position: 'absolute', 
  8.     left: `${x}%`,
  9.     top: `${y}%`,
  10.     width: '30px',
  11.     height: '30px',
  12.     background: col,
  13.     cursor: cursor || 'pointer',
  14.     color: 'white'
  15.   })
  16.   return box
  17. }
  18.  
  19. const NUM = 10;
  20. for (let i = 0; i < NUM; i++) 
  21.   box(
  22.     Math.random() * 100, 
  23.     Math.random() * 100)
  24.  
  25.  
  26. let destX = destY = x = y = 0;
  27. const blue = box(destX, destY, 'blue', 'default')
  28. const info = box(0, 30, 'gray')
  29. info.innerHTML = 'click the red boxes'
  30. Object.assign(info.style, {
  31.   width: '100%', 
  32.   padding: '.5em',
  33.   fontFamily: 'sans-serif'
  34. })
  35.  
  36. document.addEventListener('click', e => {
  37.   const curr = e.target
  38.   if (curr.classList.contains('red-box')) {
  39.     destX = curr.offsetLeft
  40.     destY = curr.offsetTop
  41.     curr.style.background = 'black'
  42.     setTimeout(() => curr.style.background = 'red', 700)
  43.     if (info.parentNode != null) { 
  44.       info.parentNode.removeChild(info);
  45.     }
  46.   }
  47. })
  48.  
  49. function loop() {
  50.   x += (destX - x) / 12
  51.   y += (destY - y) / 12
  52.   blue.style.transform = `translate3d(${x}px, ${y}px, 0)`
  53.   requestAnimationFrame(loop)
  54. }
  55. loop()

Click a red box, watch the blue box animate…

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