JQuery: Selecting appropriate content based on anchor in URL when displaying page

If a user is given a link to your page, you can automatically display certain content depending on the anchor provided in the url.


This makes your page more user friendly when people copy pasta links to a friend, removing the need to provide instructions on how to navigate to the content.

First, create an anchor with a name matching the anchor.

<a href="#show-comments">Show</a>

The last bit of code on the page should execute after everything else has been initialised and set up correctly.

function displayAnchor() {
var url = document.location.toString();

// URL contains an anchor
if (url.match('#')) {
var anchor = '#' + url.split('#')[1];
$('a[href="' + anchor + '"]').trigger('click');

It checks if the URL given contains an anchor name ("#show-comments" in this instance) and tries to trigger the click event on the corresponding element.

This will only work if your "href" is the target anchor name (href="#anchor") and not something like href="/page/something.html#anchor".

If it is the latter, you'll need a different selector.

You can also use an animation to slide to an anchor.

[ Source ]

Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog