Skip to content

Instantly share code, notes, and snippets.

@balupton balupton/
Created May 8, 2013

What would you like to do?
DocPad: Snippet: Make headers anchors in your page

Snippet: Make headers anchors in your page

Taken from the DocPad Website - source

class App
	constructor: ->
		# Anchor Change Event
		@$window.on('anchorchange', @anchorChange)

		# State Change Event
		@$window.on('statechangecomplete', @stateChange)

	anchorChange: =>
		hash = History.getHash()
		return  unless hash
		el = document.getElementById(hash)
		return  unless el
		if el.tagName.toLowerCase() is 'h2'

	stateChange: =>
		$('h1,h2,h3,h4,h5,h6').each ->
			return  if @id
			id = @innerText.toLowerCase().replace(/\s+/g,' ').replace(/[^a-zA-Z0-9]+/g,'-').replace(/--+/g,'-').replace(/^-|-$/g,'')
			return  if document.getElementById(id)
			@id = id
			@setAttribute('data-href', '#'+@id)  unless @getAttribute('data-href')
			@className += 'hover-link'  unless @className.indexOf('hover-link') isnt -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.