Search code examples
jquerycssautomationarticle

Use jQuery to automate links to chapters within a page?


The page in question: http://wlvrtn.com/sites/nms-chapters/page.php

This page currently is made of up 3 chapters, each contained in their own article tags. In the future, I'll add additional chapter articles, as well as chapter links in the floating chapter nav.

What I'd like to achieve:

I want to automate the chapter nav link destinations via jQuery, such that the first link in the list points to the first article on the page, the second link points to the second article, and so on.

I.e., if I add a fourth chapter article, I don't want to have to give it the id "article-04"; I want the fourth link in the chapter nav, when added, to know it should point to the new article. I'm guessing that "nth-child" plays into this, but I'm too new to know.

Thanks, xo


Chapter Nav:

<nav id="chapters">
  <ul>
     <li><a href="#">Chapter One</a></li>
     <li><a href="#">Chapter Two</a></li>
     <li><a href="#">Chapter Three</a></li>
  </ul>
</nav>

Chapter Article:

<article class="clearfix">
  <h1>Chapter One</h1>
</article>
<article class="clearfix">
   <h1>Chapter Two</h1>
     <p>And so on...</p>

Solution

  • How about something like this (demo)?

    $(function(){
    
        // find the nav & headers
        var nav = $('#chapters li a'),
            articles = $('#main article > h1');
    
        // now assign an id/href to each
        nav.each(function(i){
            nav.eq(i).attr('href', '#article-' + i);
            articles[i].id = 'article-' + i;
        });
    
    });