Theme & Front End JavaScript Beginner

Add a “Back to Top” Button

Show a round button in the bottom corner after visitors scroll down, which takes them back to the top of the page.

Tested on WordPress 7.1 No plugin needed Updated
script.js 24 lines
document.addEventListener( 'DOMContentLoaded', () => {
	const button = document.createElement( 'button' );
	button.type = 'button';
	button.className = 'nahnu-to-top';
	button.setAttribute( 'aria-label', 'Back to top' );
	button.textContent = '↑';
	button.hidden = true;
	document.body.appendChild( button );

	const style = document.createElement( 'style' );
	style.textContent = '.nahnu-to-top{position:fixed;right:20px;bottom:20px;z-index:999;width:44px;height:44px;border:0;border-radius:50%;background:#15131F;color:#fff;font-size:20px;cursor:pointer;box-shadow:0 6px 16px rgba(0,0,0,.25)}.nahnu-to-top[hidden]{display:none}';
	document.head.appendChild( style );

	const toggle = () => {
		button.hidden = window.scrollY < 600;
	};
	window.addEventListener( 'scroll', toggle, { passive: true } );
	toggle();

	button.addEventListener( 'click', () => {
		const smooth = ! window.matchMedia( '(prefers-reduced-motion: reduce)' ).matches;
		window.scrollTo( { top: 0, behavior: smooth ? 'smooth' : 'auto' } );
	} );
} );

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.

Long articles and product lists leave visitors far from the menu. A back-to-top button saves a lot of scrolling, especially on phones.

How it works

When the page is ready, the script adds a button and a few lines of CSS to the page. The button stays hidden until the visitor has scrolled 600 pixels, using a passive scroll listener that doesn’t slow scrolling down.

Clicking it scrolls to the top, smoothly unless the visitor has asked their device to reduce motion. The button has an aria-label, so screen readers announce it as “Back to top”.

Things to watch

  • Change the colours in the CSS string to match your brand.
  • If you have a chat widget in the same corner, change right to left or raise bottom.

How to test it

Open a long post and scroll down. The button should appear; clicking it should take you back to the top.

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