Back link with and jQuery (and WordPress)

There are times in which you may need to add a back link to the navigation of a WordPress site, and especially for web apps.

As well as the skip link, you may want some specific browser to find it when they need it.

It is a good practice to avoid inline instructions and styling, and to move all the Javascript in the footer when possible.

The markup and the Javascript

First step, we need a back link. It is a navigation feature, so I put it in the header.php file.

<div id="backLink-container"><a>Take me back!</a></div>

The script below requires jQuery. Many framework and CMS come with jQuery. So I will assume that it has been already loaded.

<script type="text/javascript">
(function ($) {
  $(document).ready(function () {
    // Adds a little magic to the back link button
    $('.backLink').click(function(event) { event.preventDefault(); history.back(1);
  });
}); })(jQuery);
</script>

A class or an ID can tell many things. While I often follow common rules (see SMACSS for example), in this case I used a camelCase naming. In short backLink instead of back-link. The name helps me to quickly understand that this element is bond to a Javascript code - that ultimately defines its behavior.

I wrapped the link within a div. I noticed that doing so I compensate for some weirdos on some browser.

On the other hand, navigations blocks are often composed by unordered list and links inside a nav or a div, so having a similar markup will make the styling easier.

Last, even if the block that contains the back link is in the header.php file, the Javascript code is in the footer.php, so that the markup stays clean.

A little bit of styling

Let’s see a bit of CSS that we can apply to it. The back link should be visible only on mobile and an eventual image or icon should to be loaded only on that device. Here a “mobile-first” approach.

#backLink-container {
  display: block;
  position: absolute;
  top: 0;
  left: 0; }

.backLink {
  display: block;
  width: 30px;
  height: 30px;
  background-image: url(/images/backLink.png); }

// iPad threshold is on 48em for portrait mode  
@media ( min-width: 48em ) {

  #backLink-container {
    display: none; }

  .backLink {
    display: none;
    text-indent: -1000em;
    background-image: none;  }
}

The styling above is merely a starting point, you may want to add your own. Hopefully this will help making up your responsive navigation to play with.