Created
June 20, 2011 14:47
-
-
Save seutje/1035745 to your computer and use it in GitHub Desktop.
jQuery plugin to wrap every x items with element y
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
// Expose the Array.reverse() method on jQuery objects | |
$.fn.reverse = [].reverse; | |
/** | |
* takes a jQuery collection and wraps each x items with element y | |
* kinda nasty looking though | |
* example: $('.foo').children().wrapInChunks('<div class="bar" />', 3); | |
* wraps every 3 children of .foo in div.bar | |
* NOTE: Needs a way to distinguish the wrapper from the wrapped elements, | |
* ergo, wrapping classless, IDless DIVs with classless, IDless DIVs will error out | |
*/ | |
jQuery.fn.wrapInChunks = function(html, chunkSize) { | |
chunkSize = chunkSize || 1; | |
var items = this.get(), | |
collection = this, | |
rows = [], | |
cur = rows[0] = html, | |
amount = this.length, | |
helper = function(times, $el) { | |
var $that = $el, | |
$html = $(html), | |
classes = $html.attr('class'), | |
myId = $html.attr('id'), | |
checker = $html[0].nodeName, | |
classes2, | |
myId2, | |
checker2; | |
checker += classes.length ? '.' + classes.split(' ').join('.') : ''; | |
checker += myId && myId.length ? '#' + myId : ''; | |
while (times--) { | |
$that = $that.prev(); | |
classes2 = $that.attr('class'); | |
myId2 = $that.attr('id'); | |
checker2 = $that[0].nodeName; | |
checker2 += classes2.length ? '.' + classes2.split(' ').join('.') : ''; | |
checker2 += myId2 && myId2.length ? '#' + myId2 : ''; | |
if (!$that.is(checker) && collection.filter(checker2).length) { | |
$el = $el.add($that[0]); | |
} | |
} | |
return $el; | |
}; | |
return this.each(function(i, el) { | |
var $this = $(this); | |
i++; | |
if (i % chunkSize == 0) { | |
var num = chunkSize, | |
$that = $this; | |
$this = helper(num, $that); | |
$this.reverse().wrapAll(html); | |
} | |
else { | |
if (i == amount) { | |
var num = i % chunkSize -1, | |
$that = $this; | |
$this = helper(num, $that); | |
$this.reverse().wrapAll(html); | |
} | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
seriously need a better way to check if we are still dealing with elements in the original collection
ergo, get rid of (!$that.is(checker) && collection.filter(checker2).length) and everything that's got to do with it