In this lesson I manipulate the text-shadow 'style' of an element depending on where the mouse is positioned.
First I grab the 'hero' <div> and 'text' element. I initialise the 'walk', which sets the bounds on the shadow size. I listen for 'mousemove' on 'hero' and run shadow(e).
In shadow(e) - Set the width and height to match the hero 'offsetWidth' and 'offsetHeight' using es6 destructuring. (const { offsetWidth: width, offsetHeight: height } = hero). Also get the position of the cursor based on the event offset (let { offsetX: x, offsetY: y } = e).
Next detect if the element is no longer equal to the original target (this !== e.target), this checks if the user moved onto an overlapping element. If so, the X,Y values would then point to that element's origin and would no longer be the same values as if the user was hovering over the 'hero'. Because of this, calculate and set the X,Y values to match the new targets' offset plus the current X,Y (x = x + e.target.offsetLeft). This ensures the X,Y values are still the same as they would be if there was no overlapping element.
Next create new 'xWalk' and 'yWalk' variables that converts the walk into the bounds for X and Y (xWalk = Math.round((x / width * walk) - (walk / 2))). Finally set the text shadow value on the 'text' element by injecting xWalk and yWalk (text.style.textShadow = `${xWalk}px ${yWalk}px 0 rgba(0,0,0,0.6)`).
See the Pen
JavaScript30 - 16 - Mouse Move Shadow by Corey Noble (@CoreyNoble)
on CodePen.