How to set up smooth scrolling for hash links in WordPress

Posted on
5/5 - (268 votes)

There are several ways to scroll smoothly when clicking on jump links (anchors linking to sections within the same page) and the simple code below is from Paulund’s site.

But first the sample markup:

<a href="#services">Jump to services</a>

<div id="services">
<p>Praesent tincidunt felis ed, a euismod quam dapibus tempus. Phasellus accumsan tellus dui. Nam ullamcorper hendrerit nunc, id eleifend dui fermentum sed. Mauris pulvinar non leo in iaculis. Nunc consequat mi lectus, sit amet egestas felis cursus sed. Proin lacinia nisl eu blandit sodales. Maecenas ultrices urna sed lectus pulvinar laoreet ut in ante. Vestibulum et maximus risus. Praesent eu sodales nunc, et accumsan lectus.</p>
</div>

Step 1

Create a file named say, global.js in your child theme’s js directory (create, if not present) having the following code:

jQuery(function( $ ){

	// Smooth scrolling when clicking on a hash link
	$('a[href^="#"]').on('click',function (e) {
		e.preventDefault();

		var target = this.hash;
		var $target = $(target);

		$('html, body').stop().animate({
			'scrollTop': $target.offset().top
		}, 900, 'swing');
	});

});

If you have a fixed header and would like to set an offset for the scroll position, subtract the height of your fixed element like so:

'scrollTop': $target.offset().top-120

where 120 is the height in px of the fixed header in this example.

To set an offset at viewport widths greater than a specific width, use this sample global.js instead:

jQuery(function( $ ){

	// Smooth scrolling when clicking on a hash link
	$('a[href^="#"]').on('click',function (e) {
		e.preventDefault();

		var target = this.hash;
		var $target = $(target);

		if ( $(window).width() > 1023 ) {
			var $scrollTop = $target.offset().top-120;
		} else {
			var $scrollTop = $target.offset().top;
		}

		$('html, body').stop().animate({
			'scrollTop': $scrollTop
		}, 900, 'swing');
	});

});

Step 2

Add the following in child theme’s functions.php:

// Enqueue site-wide scripts
add_action( 'wp_enqueue_scripts', 'sk_enqueue_scripts' );
function sk_enqueue_scripts() {

	wp_enqueue_script( 'global', get_stylesheet_directory_uri() . '/js/global.js', array( 'jquery' ), '', true );

}

That’s it.