Animated underlines
Based on https://css-tricks.com/svg-line-animation-works/
by sperske
HTML
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.css">
<div>
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p>
<svg viewBox="0 0 0 0">
<path class="path" fill="none" stroke="#0d8065" stroke-width="2.5" d="" />
</svg>
</div>
CSS
:root {
--lineLength: 0;
}
div {
padding: 1rem;
}
svg {
position: absolute;
top: 1rem;
pointer-events: none;
overflow: visible;
}
.path {
stroke-dasharray: var(--lineLength);
stroke-dashoffset: var(--lineLength);
}
@keyframes dash {
to {
stroke-dashoffset: 0;
}
}
JavaScript
const p = document.querySelector('p')
const s = document.querySelector('svg')
const underline = s.querySelector('path')
const BEND_RADIUS = 3
function render() {
// size selection box to match element
s.viewBox.baseVal.height = p.clientHeight
s.viewBox.baseVal.width = p.clientWidth
// position path to match selection
const selection = document.getSelection();
if (selection.rangeCount > 0 && selection.toString().length > 0) {
document.documentElement.style.setProperty('--lineLength', underline.getTotalLength());
underline.style.animation = "dash 2s linear alternate infinite"
const range = selection.getRangeAt(0);
const rect = range.getBoundingClientRect();
const path = [
"m 0 0", // start at the top left
`l 0 ${rect.y - BEND_RADIUS}`, // move down to 2px above the line start
`s 0 ${BEND_RADIUS} ${BEND_RADIUS} ${BEND_RADIUS}`, // bend
`l ${rect.x} 0`, // extend to start of line
]
underline.setAttribute('d', path.join(' '))
} else {
document.documentElement.style.setProperty('--lineLength', 0);
underline.style.animation = ''
}
}
render()
window.onresize = render
window.onmouseup = render