1

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.)

Community
  • 1
  • 1
ELLIOTTCABLE
  • 17,185
  • 12
  • 62
  • 78

2 Answers2

1

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).

bryanbraun
  • 3,025
  • 2
  • 26
  • 38
0

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.

ELLIOTTCABLE
  • 17,185
  • 12
  • 62
  • 78
  • If the only differentiating factor between jQuery and the rest is that proprietary (and confusingly named) `:header` selector, you could just expand it to its standardized equivalent. It's probably not worth including the entire jQuery library just for one selector. – BoltClock Jul 28 '15 at 10:54
  • Yeah, that's my assumption; but writing out all that DOM code by hand wasn't appealing. I couldn't find any question along these lines, to my surprise, here on S.O.; so I posted, in hopes somebody could one-up me with the clean equivalent for others' future discovery. – ELLIOTTCABLE Jul 28 '15 at 11:01