Shlomif's Technical Posts Community - jQuery Tip: Adding Self-Links to Headings [entries|archive|friends|userinfo]
Shlomif's Technical Posts Community

[ userinfo | livejournal userinfo ]
[ archive | journal archive ]

jQuery Tip: Adding Self-Links to Headings [Apr. 24th, 2008|07:33 pm]
Previous Entry Add to Memories Tell a Friend Next Entry

shlomif_tech

[shlomif]
[Tags|, , , , , , , , , , ]
[Current Location |Home]
[mood |playful]
[music |B'Witched - C'est La Vie]

On my homepage, I have many <h2>, <h3>, etc. tags with id attributes in them so one can link directly to the middle of the page. I have written a Website Meta Language API that allows one to generate a table of contents for the page based on them. However, recently I also looked for a way to have a link to their anchors somewhere close to them.

I eventually decided to try doing it using JavaScript and jQuery. It took me a bit of documentation lookup, trial and error and consulting people on IRC, but I ended up with:

<script type="text/javascript">
<!--
$("h1[id],h2[id],h3[id],h4[id],h5[id],h6[id]").each(
function(i){
$(this).append( ' <span class="selfl">[<a href="#' + 
this.id + '">link</a>]</span>' )
})
-->
</script>

Now for some explanations:

  1. The $("h1[id]...") construct selects all the headings with id's. There may be a shorter way to do it (comments are welcome).
  2. The each method iterates over all of them and calls the closure inside. The closure sets the "this" variable to the current element, and accepts its index there (the "i" variable). In our case, we're not making use of the index.
  3. $(this) constructs a jQuery object from "this".
  4. .append() appends an expression to the inner HTML of the element. I add a little HTML there. this.id may result in an XSS attack if you have a really funky (and probably invalid) ID, but since I have control over my ID's it's OK.

You can see the result, in the headings of the presentations' page (for example), as long as you don't have JavaScript turned off. jQuery seems very nice, and I'm looking forward to making even more use of it where appropriate.

linkReply