Skip to content

Handling onpage hash links #586

@rkyoku

Description

@rkyoku

Hi,

I am having trouble with simple hash links : <a href="#my-section">link</a>

I specified {click: false} in the Page.js options, because there are some links I do not want handled by Page.js.

However, in my click handler, I detect the hashtag, and I return true (using jQuery) so that the browser updates the URL and scrolls to the section with that ID.

In that scenario, I am not calling page($this.attr('href')) like I do for "normal" links.

Strangely enough, it seems that Page.js still intercepts that link (or that change of URL) and matches the route again, which causes a "reload" (SPA-like) of my page.

How should I handle onpage hash links?

$(document.body)
	.on('click', 'a', function(e) {
		const $a = $(this);

		console.log('click A', this, $a.attr('href'));

		/** previous code (not working)
		if ($a.attr('href').charAt(0) === '#' || $a.hasClass('api-link') || $a.hasClass('api-download'))
			return true;
		*/

		// New attempt (not working either)
		if ($a.attr('href').charAt(0) === '#' || $a.hasClass('api-link') || $a.hasClass('api-download')) {
			console.log('follow link!');

			e.preventDefault();
			e.stopImmediatePropagation();

			// Not working either
			// const url = location.href;
			// location.href = $a.attr('href');
			// history.pushState(null,null, url + $a.attr('href'));

			// Still not working
			window.location.hash = $a.attr('href');

			return false;
		}

		//
		// Standard behavior for `<a href="/my/new/url">` links
		//
		console.log('Clicking on link', $a.attr('href'));
		e.preventDefault();
		page($a.attr('href'));
	})
;

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions