メニュー

🏷️WordPressでよく使うアンカーリンク向けjQuery

ヘッダーにはid名「header」を指定。
即時関数と厳格モードは必要に応じて消せ消せ消せ消せ(´・ω・`)

(() => {
'use strict';
	
	jQuery( function($) {
		const headerH = Math.floor( headerH = $( '#header' ).height() );
		const url_host = jQuery( location ).attr( 'hostname' );
		const url_path = jQuery( location ).attr( 'pathname' )
		$( 'a[href*="#"]' ).on( 'click', function() {
			if( this.hostname === url_host && this.pathname === url_path ) {
				const speed = 700;
				const target = $( this.hash === '#' || '' ? 'html' : this.hash );
				const pos = !target[0] ? 0 : target.offset().top - headerH;
				$( 'html, body' ).animate( { scrollTop:pos }, speed, 'swing' );
				return false;
			}
		});
	});
	
})()

同一ドメイン&ページ内アンカーリンクでもうまくいく。

OLD

2025/06/27

外部サイトへのアンカーリンクには注意(´・ω・`)

(() => {
'use strict';
	
	jQuery( function($) {
		const headerH = $( '#header' ).height();
		$( 'a[href*="#"]' ).on( 'click', function() {
			const speed = 700;
			const target = $( this.hash === '#' || '' ? 'html' : this.hash );
			const pos = !target[0] ? 0 : target.offset().top - headerH;
			$( 'html, body' ).animate( { scrollTop:pos }, speed, 'swing' );
			return false;
		});
	});
	
})()