Created
March 31, 2014 20:49
-
-
Save mikedamage/9901913 to your computer and use it in GitHub Desktop.
Ancestry climber jQuery plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### | |
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