Happylab Logo
Published on

Day16: Mouse Shadow

Authors

Introduction: How to use JavaScript and CSS to create text shadow effects that follow mouse movement.

Project Page: https://iris1114.github.io/javascript30/16_Mouse-Move-Shadow/

HTML

  • Contains an editable heading '🔥WOAH!' within a div container.
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Mouse Shadow</title>
  </head>
  <body>
    <div class="hero">
      <h1 contenteditable>🔥WOAH!</h1>
    </div>
  </body>
</html>

CSS

  • Sets up basic page styling including fonts, colors, and layout
  • Initial text shadow effect for the h1 heading
html {
  color: black;
  font-family: sans-serif;
}

body {
  margin: 0;
}

.hero {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  color: black;
}

h1 {
  text-shadow: 10px 10px 0 rgba(0, 0, 0, 1);
  font-size: 100px;
}

JavaScript

  • Uses JavaScript to listen for mouse movement and dynamically update text shadow effects
const hero = document.querySelector('.hero')
const text = hero.querySelector('h1')
const walk = 100 // 100px

function shadow(e) {
  const { offsetWidth: width, offsetHeight: height } = hero
  let { offsetX: x, offsetY: y } = e

  if (this !== e.target) {
    x = x + e.target.offsetLeft
    y = y + e.target.offsetTop
  }

  const xWalk = Math.round((x / width) * walk - walk / 2)
  const yWalk = Math.round((y / height) * walk - walk / 2)

  text.style.textShadow = `
    ${xWalk}px ${yWalk}px 0 rgba(255,0,255,0.7),
    ${xWalk * -1}px ${yWalk}px 0 rgba(0,255,255,0.7),
    ${yWalk}px ${xWalk * -1}px 0 rgba(0,255,0,0.7),
    ${yWalk * -1}px ${xWalk}px 0 rgba(0,0,255,0.7)
  `
}

hero.addEventListener('mousemove', shadow)

Note

  • Uses offsetWidth and offsetHeight to get container dimensions
  • Uses offsetX and offsetY to get mouse coordinates relative to the container
  • Dynamically calculates shadow offsets and applies multiple shadow effects