This is day 22 in my #javascript30 journey. This is the free course from Wes Bos that lets you brush up on your JavaScript skills via 30 projects.
Yesterday we explored geolocation. You can keep track of all the projects we’re building here.
Today we’re exploring follow along link highlighting.
Day 22 - Follow Along Link highlighting
This is the first step in a multi-part project that we will be completing. The aim of today is to create a white background ‘pill’ that will follow the cursor around the page to highlight the current (or latest) link that the cursor rolled over.
First up we will need to access all of the links on the page and listen for when the cursor hovers over them.
const triggers = document.querySelectorAll('a')
const highlight = document.createElement('span')
highlight.classList.add('highlight')
document.body.append(highlight)
function highlightLink(e) {
console.log('Highlight', e)
}
triggers.forEach(a => a.addEventListener('mouseenter', highlightLink))
Now we have a message being sent to the console every time the mouse hovers over a link:
Next up we need to figure out the hight and width that is required for the highlight to match the link. We want the entire link to be highlighted so this is an important step :).
To do this we will use getBoundingClientRect()
. This gives us all of the information about the link, where it lives on the page and how much room it takes up. Awesome.
This gives us an object that looks like this:
ClientRect {
top: 100,
right: 396.78125,
bottom: 128,
left: 344.09375,
width: 52.6875
}
Using this information we are able to transform the highlight div to match the link location:
function highlightLink(e) {
const linkCoordinates = this.getBoundingClientRect()
highlight.style.width = `${linkCoordinates.width}px`
highlight.style.height = `${linkCoordinates.height}px`
highlight.style.transform = `translate(${linkCoordinates.left}px, ${linkCoordinates.top}px)`
}
This is looking pretty great:
The final task to do it to ensure that this works when the page is scrolled. To do this we need to calculate the height of the page that is no longer visible. We can do this by calculating and adding window.scrollY
:
function highlightLink(e) {
const linkCoordinates = this.getBoundingClientRect()
const coords = {
width: linkCoordinates.width,
height: linkCoordinates.height,
top: linkCoordinates.top + window.scrollY,
left: linkCoordinates.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)`
}
Now this is all working smoothly (regardless of the scroll location):
Now we have a link highlighter (although it doesn’t do much at the moment)!
You can play around with the link highlighter here.
You can keep track of all the projects in this JavaScript30 challenge here.