This is the first part of a project where we want to build a replica of the navigation bar from Stripe. So in this first exercise, we build a link higlighter which will transtition from one link to another with a smoothie effect adding a class to the link.
-
We start creating an
span
element, adding it thehiglight
class and appending it to thebody
. -
Then when the event is triggered we have to calculate the position of the trigger and add these values to the
highlight
class.function highlightLink() { const linkCoords = this.getBoundingClientRect(); const coords = { width: linkCoords.width, height: linkCoords.height, top: linkCoords.top + window.scrollY, left: linkCoords.left + window.scrollX }; highlight.style.width = `${coords.width}px`; highlight.style.height = `${coords.height}px`; highlight.style.transform = `translate(${coords.left}px, ${coords.top}px)`; }
What is important about the function
above is:
- How we calculate the position of the trigger(
this
) represented by aa
with getBoundingClientRect. - How we add the amount of scrolled screen with
.scrollX
andscrollY
, to position correctly the 'span' element. - How we use
translate
instead of defining directly thetop
andleft
properties. Doing it this way we achieve a smoothier effect when we move from a link to another one.
- mouseenter: user enters with the mouse inside the trigger element