Question

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>
Was it helpful?

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;
    });

});

OTHER TIPS

There's a lot of jquery tutorial for anchor link scroll with jquery. i personally use this one on one of my projects

try this tutorial:

http://tympanus.net/codrops/2011/12/05/lateral-on-scroll-sliding-with-jquery/

:)

A relatively simple approach to meeting your requirements would be this, though it could certainly be optimised:

$('h1').each(
    function(){
        var that = $(this),
            txt = that.text();
        that[0].id = txt.replace(/\s+/,'');

        if (!$('#toc').length){
            $('<ul />', { id : 'toc' }).prependTo('body');
        }

        var li = $('<li />').appendTo('#toc');
        $('<a />', {'href' : '#' + that.text().replace(/\s+/,''), text : that.text()}).appendTo(li);
    });

JS Fiddle demo.

References:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top