In continuation of Follow Along Link Highlighter, I create a flexible dropdown navigation inwhich the size of any dropdown item can be dynamic. As the user hovers on each dropdown item, a puppy <div> follows along in both size and position to transition into the background for that newly shown dropdown item.
First I get the 'nav' and the 'triggers' (<li>) as well as the puppy <div> 'background'.
I listen for:
-
triggers.forEach(trigger => trigger.addEventListener)
- 'mouseenter', handleEnter()
- 'mouseleave', handleLeave()
In handleEnter() - First add a class of '.trigger-enter' to the trigger. This class changes 'display:none' to 'display:block'. The class is added on a delay, so use an arrow function to check if the class is there. If so, add a second class of '.trigger-enter-active'. This is known as stepping in an animation. First display it, then transition it. (setTimeout(() => this.classList.contains('trigger-enter' && this.classList.add('trigger-enter-active', 150);). Then add a class of '.open' to 'background'.
Next get the 'dropdown' and its bounding rectangle, also get the bounding rectangle of the 'nav'. Using the 'dropdown' bounding rectangle, calculate the 'width' and 'height values that 'background' will need.
Using 'nav' and 'dropdown' bounding rectangles, calculate the height, width, and position that 'background' will need. Use 'nav' as an anchor for positioning.
const coords = {
width: dropdownCoords.width,
height: dropdownCoords.height,
top: dropdownCoords.top - navCoords.top,
left: dropdownCoords.left - navCoords.left
}
Finally set the 'background' styles by injecting the 'coords' into the style attributes of 'background' using es6 template strings. (background.style.setProperty('width', `${coords.width}px`)).
In handleLeave() - Hide the elements. Remove the classes '.trigger-enter' and '.trigger-enter-active' from the trigger. Remove the class of '.open' from 'background'.
See the Pen
JavaScript30 - 26 - Stripe Follow Along Nav by Corey Noble (@CoreyNoble)
on CodePen.