Skip to content

Instantly share code, notes, and snippets.

@balupton
Created May 8, 2013 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save balupton/5541095 to your computer and use it in GitHub Desktop.
Save balupton/5541095 to your computer and use it in GitHub Desktop.
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'
			$(el).trigger('select')
		else
			$(el).ScrollTo(@config.sectionScrollOpts)

	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