Making your web site's navigation mobile friendly

Wednesday 16 November 2011

I am currently working on a project to convert a web site to a responsive design. The site's navigation has a lot of links arranged in list format so, rather than displaying the navigation in list format on mobile devices which would push the page content off the screen, I thought I would use jQuery to convert the navigation to a select list if a mobile device is being used. Here's how I plan to do it.

Firstly, add the following HTML inside your web page's BODY tag to create a list.

<ul id="navigation">
  <li><a href="http://www.simonbingham.me.uk/">Link 1</a></li>
  <li><a href="http://www.simonbingham.me.uk/">Link 2</a></li>
  <li>
    <a href="http://www.simonbingham.me.uk/">Link 3</a>
    <ul>
      <li><a href="http://www.simonbingham.me.uk/">Link 4</a></li>
      <li><a href="http://www.simonbingham.me.uk/">Link 5</a></li>
      <li><a href="http://www.simonbingham.me.uk/">Link 6</a></li> 
    </ul>
  </li>
  <li><a href="http://www.simonbingham.me.uk/">Link 7</a></li>
  <li><a href="http://www.simonbingham.me.uk/">Link 8</a></li>
</ul>

Now add the following JavaScript inside the HEAD tag.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
  $(document).ready(function() {

  // detect whether tablet/mobile device is being used
  if($(document).width()<=767) {
    // create a new SELECT tag
    var $select = $("<select id='new-navigation' />"); 

    // loop through each A tag in navigation
    $("#navigation").find("a").each(function() {
      // create a new OPTION tag
      var $option = $("<option />");

      // when the OPTION tag is clicked redirect the user using the href value of the A tag
      $option.html($(this).html()).val(this.href).click(function() {
        window.location.href = $(this).val();
      });

      // append the OPTION tag to the SELECT tag
      $select.append($option);
    });

    // replace the original navigation with the new SELECT tag and it's associated options
    $("#navigation").replaceWith($select); 
  };
});
</script>

Done! :-)

Download Sample Code


Tags

HTML (7) jQuery (7) Responsive Design (3)

Share


Comments

Be the first to add a comment!

Add Comment

Your email address will not be displayed on this blog.

The URL of your blog or web site.