← All examples

JavaScript Navigation

Scroll-spy active section highlight

Highlights the table-of-contents link matching the section currently visible on screen.

Code to copy

var heads = document.querySelectorAll('h2[id], h3[id]');
if (heads.length && 'IntersectionObserver' in window) {
  var obs = new IntersectionObserver(function (entries) {
    entries.forEach(function (en) {
      if (en.isIntersecting) {
        document.querySelectorAll('a[href^="#"]').forEach(function (a) {
          var on = a.getAttribute('href') === '#' + en.target.id;
          a.style.fontWeight = on ? '700' : '';
          a.style.background = on ? '#fff3a8' : '';
        });
      }
    });
  }, { rootMargin: '0px 0px -70% 0px' });
  heads.forEach(function (h) { obs.observe(h); });
}

How to use this example

  1. Copy the code with the button above.
  2. Install JustZix (2 minutes) and open the extension on the target page.
  3. Add a new rule matching that page.
  4. Paste the code into the rule's JavaScript panel and save — it runs on every page visit.

Rate this example

No ratings yet — be the first.

Does this example work?

Snippets are useless without somewhere to paste them.

JustZix takes 2 minutes to install and runs your code on every matching page. No account, no payment.

Download free See use cases