ELLIOTTCABLE
ELLIOTTCABLE

Reputation: 18088

What's the simplest, safest way to dynamically add anchor-able ids to HTML headers?

I want a Tumblr theme to add link-able anchors to every header in the content of a post. I don't have access to, or control over, the rendering of that content; Tumblr tends to spit out plain <h2>s and similar, for Markdown headers:

## Hello, πŸ’– friend πŸ’!        ->       <h2>Hello, πŸ’– friend πŸ’!</h2>

I'd like to ensure that any section of a post can be hyperlinked directly to with an anchor link, such as http://thing.place/post/12345#hello-friend. Has anybody got a simple, fairly universal JavaScript snippet to sanitize any header element's content, and add it to that header as an id?

(Presumably, if you've already written this for yourself; you might also have some additional code to add an anchor-link indicator that self-links, as well; share it if you've got it.)

Upvotes: 2

Views: 386

Answers (2)

bryanbraun
bryanbraun

Reputation: 3365

I maintain a project that does what you describe: AnchorJS

Once you include the script, you can pick which elements it adds anchors to with a selector:

// Add anchors to all h1's and h2's on the page
anchors.add('h1, h2');

It doesn't have any dependencies on Jquery or Lodash, in case that's an issue with Tumblr (I'm not familiar enough with Tumblr to know the constraints there).

Upvotes: 1

ELLIOTTCABLE
ELLIOTTCABLE

Reputation: 18088

I've got a really naΓ―ve solution that depends upon both jQuery and Lodash (and I do mean full jQuery, as Zepto and friends don't include :header); but lightweight, elegant, pure-JavaScript solutions are preferred:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.min.js"></script>
<script>
   jQuery.noConflict(true)(function($){
      var lodash = _.noConflict()
        , anchor = "\u2693\uFE0E"

      $(':header')
      .wrap(function(){
         var wrapper = document.createElement('header')
           ,   title = lodash.kebabCase( $(this).text() )

         return $(wrapper).attr('id', title) })
   })
</script>

This does the extra work of adding a semantic <header> element that I'm planning on using for other purposes, but that may not be necessary.

Upvotes: 0

Related Questions