W3 Mind Logo
Home » Smooth scrolling for hash links in WordPress

Smooth scrolling for hash links in WordPress

Here is the markup code.
				
					<a href="#aboutme">Go to About Me</a>

<div id="aboutme">
<h3>About Me</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus fermentum, felis sit amet faucibus dictum, arcu felis mollis neque, in tristique enim neque sit amet velit. Nulla tristique sapien in libero molestie, a egestas quam bibendum. Suspendisse nec efficitur lacus. Duis interdum nisl eros, sed elementum massa efficitur eu.</p>
</div>
				
			

Step 1

You need to create a file global.js in your child theme’s js directory (create, if not present) with 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 are making 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 of the fixed header in px in the below 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 code in your 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 );

}
				
			
About Author
Picture of W3Mind

W3Mind

W3Mind focuses on Blogging, Make Money Online, SEO, Business Blogging, Social Media, WordPress, Internet Tools, Web Design and Development.
Give it a Share
Facebook
Twitter
LinkedIn
You May Also Like
How to
START A
BLOG
(step by step)
Load WordPress Sites in as fast as 37ms!