Can't Touch This Button
November 7, 2025
A button that runs away from your cursor when you get too close. The core mechanic uses distance detection and vector math to calculate where the button should escape.
How It Works
Track the mouse position, calculate the distance to the button, and when the cursor gets within a threshold (150px), move the button in the opposite direction.
1.canvas.addEventListener("mousemove", (e) => {2. // Get mouse position3. const rect = canvas.getBoundingClientRect();4. const mouseX = e.clientX - rect.left;5. const mouseY = e.clientY - rect.top;6.7. // Get button position8. const btnRect = button.getBoundingClientRect();9. const btnCenterX = btnRect.left + btnRect.width / 2 - rect.left;10. const btnCenterY = btnRect.top + btnRect.height / 2 - rect.top;11.12. // Calculate distance13. const dx = mouseX - btnCenterX;14. const dy = mouseY - btnCenterY;15. const distance = Math.sqrt(dx * dx + dy * dy);16.17. // If too close, escape!18. const threshold = 150;19. if (distance < threshold) {20. // Calculate escape direction (opposite to mouse)21. const angle = Math.atan2(dy, dx);22. const escapeX = btnCenterX - Math.cos(angle) * 100;23. const escapeY = btnCenterY - Math.sin(angle) * 100;24.25. // Keep button on screen26. const newX = Math.max(10, Math.min(90, (escapeX / rect.width) * 100));27. const newY = Math.max(10, Math.min(90, (escapeY / rect.height) * 100));28.29. button.style.left = newX + '%';30. button.style.top = newY + '%';31. }32.});
The Math Breakdown
1. Distance formula: Math.sqrt(dx * dx + dy * dy) calculates how far the cursor is from the button.
2. Angle calculation: Math.atan2(dy, dx) gets the angle from the button to the cursor.
3. Opposite direction: Subtract from button position using -Math.cos(angle) and -Math.sin(angle) to move away.
4. Boundary check: Math.max(10, Math.min(90, ...)) keeps the button within 10% and 90% of the screen.
More JavaScript Snippets
Popular Articles
I Can't Believe It's Not CSS: Styling Websites with SQL
Style websites using SQL instead of CSS. Database migrations for your styles. Because CSS is the wrong kind of declarative.

How I Built an Oreo Generator with 1.1 Sextillion Combinations
Building a web app that generates 1,140,145,285,551,550,231,122 possible Oreo flavor combinations using NestJS and TypeScript.

AI Model Names Are The Worst (tier list)
A comprehensive ranking of every major AI model name, from the elegant to the unhinged. Because apparently naming things is the hardest problem in AI.