A client gave me a long page of addresses and links, a directory of manufacturers for his industrial-based site.

Converting it to html, my markup ended up something like this:

view plain print about
1<h1>Links Directory</h1>
2<h2>Alabama</h2>
3<p><strong>Company Name</strong><br />
4Address<br />
5Phone... etc
6</p>
7<p><strong>Company Name</strong><br />
8Address<br />
9Phone... etc
10</p>
11<h2>Arkansas</h2>
12<p><strong>Company Name</strong><br />
13Address<br />
14Phone... etc
15</p>
16<p><strong>Company Name</strong><br />
17Address<br />
18Phone... etc
19</p>

and so on for the various states, about 35 of 'em.

Now, I needed a list of links at the top of the page, one for each state, that would allow the user to click a state name at the top, and get scrolled down to the relevant section below.

I had two choices.. go through the code and manually make an anchor link, or come up with a dynamic solution (not a hard decision).

Also, I wanted the ability to add a new state or section to the page at any time, and not have to create another new anchor and top link, in the right order... tedious. It has to be automatic, whatever it is.

This isn't database content so, aside from a massive regEx/replace/find situation, processing the full page content, CF isn't gonna help me.

But I can do the same thing with jQuery ... dynamic javascript to the rescue, via the wonderful 'each()' method !

First, we just need a place in the markup for the links. Just below the <h1> in my markup (see above), I added this:

view plain print about
1<p class="subNav"><strong>Browse by State: </strong></p>

and this bit of code, following the normal <script src="jquery.."> etc, takes care of the rest:

view plain print about
1<script type="text/javascript">
2$(document).ready(function(){
3 $('#mainCol h2').each(function(){
4 var thisText = $(this).text();
5 var anchorText = thisText.replace(/ /g, "-");
6 var anchorLink = '<a name="' + anchorText + '"></a>';
7 var anchorText = '<a href="#' + anchorText + '">' + thisText + '</a>';
8 $(this).before(anchorLink);
9 $(anchorText).appendTo('p.subNav');
10 });
11});
12</script>

Quick-splain this code:

1 - Find each 'h2' in my page's 'mainCol' div and process through them one at a time (i.e. "each()" in jquery-speak )

2 - Get the text of the h2.

3 - Replace all spaces with hyphens (for clean link href)

4 - Set the anchor element as a js var

5 - Set the anchor link as another js var

6 - Put the anchor element before the h2

7 - Add the link to the container

This could easily be made even more dynamic, and might be the base for a jquery plugin, with some nice scroll effects added... maybe some show/hide... all sorts of options.

Let me know if you can use this and what you do with it from here...