Internal Links

When Named Anchors Don't Help

hearty fare

Working Around Named Anchors

Here's one situation where named anchors aren't a satisfactory solution.

ottogal asks...

My page has a list in the <main> part and the form in the <aside> part. On a mobile device, the parts are linearized, <main> followed by <aside>, and my aim was to enable the visitor of the page to jump down to the form. The problem is that there is a form on that same page, and when using a named anchor its fields will lose their values (becoming their defaults again). What can I do?

The Solution

ottogal says...

Because I want to stay with the get method for processing the form, at the top of <main> I inserted a button which on click will hide the <main> part. Submitting the form will reload the page (getting the values back from $_GET) and automatically show the <main> again.

  $('#hide_foo,#show_foo').on('click', function() {
    $('#foo').toggle();
});

The elements #hide_foo and #show_foo are not really buttons, but divs containing an image (kind of arrow-down and arrow-up respectively). CSS @media directives are used to show these only on small viewports. And #foo is the ID of the section of content to be hidden.

What's the Story

Every request to a page ends up being passed to the main index.php file and MODX processes the appropriate resource to generate the requested page. This means that every link, even named anchors, results in a complete re-loading of the page. In some cases, this may not be desirable behavior. So the solution here was to simply avoid using a named anchor, using a button and some Javascript to show/hide the content preceding the desired target area instead. While this solution may not satisfy all needs, it's an elegant alternative to fighting with the default behavior of named anchors.