Theme & Front End JavaScript Beginner

Add a Class to the Header When the Page Scrolls

Add an is-scrolled class to your header after the visitor scrolls, so you can shrink it or add a shadow with CSS.

Tested on WordPress 7.1 No plugin needed Updated
script.js 17 lines
document.addEventListener( 'DOMContentLoaded', () => {
	const header = document.querySelector( '.site-header, header' );
	if ( ! header ) {
		return;
	}

	const onScroll = () => {
		header.classList.toggle( 'is-scrolled', window.scrollY > 10 );
	};

	window.addEventListener( 'scroll', onScroll, { passive: true } );
	onScroll();
} );

/* Then style it in your CSS, for example:
.site-header.is-scrolled { box-shadow: 0 2px 12px rgba(0, 0, 0, .12); padding-block: 8px; }
*/

Where to add this

Recommended A code snippets plugin As a JavaScript snippet set to load in the footer.
Child theme Save it as a .js file and load it with wp_enqueue_script() from functions.php.
Page builder Your builder's custom code area, set to load in the footer.

Sticky headers often look better with a subtle shadow or a slimmer height once the page scrolls. CSS can’t detect scrolling by itself, so this tiny script adds a class you can style.

How it works

The script finds your header, first by the common .site-header class and then any <header> element, and toggles is-scrolled whenever the page is more than 10 pixels from the top. The scroll listener is passive, so it doesn’t slow scrolling.

All the visual changes happen in CSS, which keeps the effect smooth and easy to adjust.

Things to watch

  • Change the selector if your header uses a different class. With Bricks, target the header template’s element id.
  • Add transition: padding .2s, box-shadow .2s; to the header for a smooth change.

How to test it

Scroll down a page and inspect the header in DevTools. It should gain the is-scrolled class.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only