Day16 of #100DaysOfCode

Kushagra Kesav
2 min readFeb 23, 2022

--

#CodeTogether Day 16/100

Hii folks 🙌

Today I have completed the 16th video of JavaScript30!

Project 16: CSS Text Shadow Mouse Move Effect

Source: https://javascript30.com

Learnings:

Today’s goal is to make the text shadow on our header text following the mouse around the window.

First, we will need to select the div (known as hero) & text. Then we need to listen for a mousemove change on the hero div. This will call the shadow function:

const hero = document.querySelector('.hero')  
const text = hero.querySelector('h1')
function shadow(e) {
//TODO:
}
hero.addEventListener('mousemove', shadow)

Shadow Function

To make the magic happen we need some specific data. We’re going to need the width & height of the hero div along with the current location of the mouse.

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

There is some odd behavior caused by the bubbling nature of JavaScript. When the mouse hovers over any children of the hero div the event fires. This is not what we want. Instead, we will normalize it so that it ignores mousemove events on children.

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

Set the maximum amount of movements. We need to set the maximum distance that we want the text-shadow to move.

const movement = 100 // 100px

Then in our shadow() function:

//calculate the maximum movements that we want to happen (total set above)
const xMovement = (x / width * movement) - (movement / 2)
const yMovement = (y / width * movement) - (movement / 2)

Now we can use these values to style the text-shadow:

text.style.textShadow = `${xMovement}px ${yMovement}px 0 red`

There we have a text-shadow that follows us around the page:

We can always add some more text shadows in:

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

This makes it an absolute spectacle:

Today I learned (T-I-L):

  • About offsetWidth and offsetHeight
  • Dynamic Text Shadow using Javascript

That is all for Day16 ✅

Thanks for reading, See you tomorrow!

--

--

Kushagra Kesav
Kushagra Kesav

Written by Kushagra Kesav

Developer Relations | Communities | Software Engineering | https://www.linkedin.com/in/kushagrakesav

No responses yet