Skip to content

Instantly share code, notes, and snippets.

@mikedamage
Created March 31, 2014 20:49
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 mikedamage/9901913 to your computer and use it in GitHub Desktop.
Save mikedamage/9901913 to your computer and use it in GitHub Desktop.
Ancestry climber jQuery plugin
###
jQuery Ancestry Climber Plugin
Defines a class that traces an element's ancestry, executing
a callback on each ancestor.
###
class AncestryClimber
constructor: (@elem, @callback = $.noop) ->
throw new Error 'Please supply a DOM element' unless @elem
throw new Error 'Please supply a callback function' unless @callback
@$elem = $(@elem)
@iterations = 0
climbLevel: (skipStop = true) ->
@iterations += 1
$parent = @$elem.parent()
stop = @callback.call(@$elem, @iterations) is false
stop = false if skipStop
@$elem = $parent
if not stop and $parent[0].nodeName isnt '#document'
@climbLevel false
return window.AncestryClimber = AncestryClimber if typeof(jQuery) is 'undefined'
$.fn.extend climbAncestry: (cb) ->
climber = new AncestryClimber $(this), cb
climber.climbLevel()
this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment