Created
March 31, 2014 20:51
-
-
Save mikedamage/9901946 to your computer and use it in GitHub Desktop.
Ancestry climber plugin in plain JS
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. | |
*/ | |
(function() { | |
var AncestryClimber; | |
AncestryClimber = (function() { | |
function AncestryClimber(elem, callback) { | |
this.elem = elem; | |
this.callback = callback != null ? callback : $.noop; | |
if (!this.elem) { | |
throw new Error('Please supply a DOM element'); | |
} | |
if (!this.callback) { | |
throw new Error('Please supply a callback function'); | |
} | |
this.$elem = $(this.elem); | |
this.iterations = 0; | |
} | |
AncestryClimber.prototype.climbLevel = function(skipStop) { | |
var $parent, stop; | |
if (skipStop == null) { | |
skipStop = true; | |
} | |
this.iterations += 1; | |
$parent = this.$elem.parent(); | |
stop = this.callback.call(this.$elem, this.iterations) === false; | |
if (skipStop) { | |
stop = false; | |
} | |
this.$elem = $parent; | |
if (!stop && $parent[0].nodeName !== '#document') { | |
return this.climbLevel(false); | |
} | |
}; | |
return AncestryClimber; | |
})(); | |
if (typeof jQuery === 'undefined') { | |
return window.AncestryClimber = AncestryClimber; | |
} | |
$.fn.extend({ | |
climbAncestry: function(cb) { | |
var climber; | |
climber = new AncestryClimber($(this), cb); | |
climber.climbLevel(); | |
return this; | |
} | |
}); | |
}).call(this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment