Scroll · 26 of 34

Text Highlight

A highlighter mark sweeps across the words when the text scrolls into view. A background gradient whose size grows from zero, so it works on wrapping text.

HTML · CSS · JavaScript · No dependencies · MIT

HTML

<section class="text-highlight-section">
  <h2>Important <span class="marker">Concept</span></h2>
</section>

CSS

.text-highlight-section {
  min-height: 35vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.text-highlight-section h2 {
  font-size: 2.5rem;
  color: #f0f0f5;
}

/* The "marker" is a background that grows from 0% to 100% wide */
.marker {
  background: linear-gradient(120deg,
    rgba(124, 92, 255, 0.35) 0%, rgba(124, 92, 255, 0.35) 100%);
  background-repeat: no-repeat;
  background-size: 0% 100%;
  background-position: 0 0;
  padding: 0 4px;
  transition: background-size 0.8s 0.2s cubic-bezier(0.16, 1, 0.3, 1);
}

.text-highlight-section.in-view .marker {
  background-size: 100% 100%;
}

JavaScript

var section = document.querySelector('.text-highlight-section');

new IntersectionObserver(function (entries) {
  entries.forEach(function (entry) {
    entry.target.classList.toggle('in-view', entry.isIntersecting);
  });
}, { threshold: 0.25 }).observe(section);