I’m trying to build my first jQuery plug-in yet it’s proving to be more difficult than I thought.
What I’m trying to achieve is something like this where you name the selector and pass how many items should be in a row.
$('#photo-gallery').grid(3);
Then the plugin function would select the nth-child(Xn) of the direct child elements of #photo-gallery where X is the option passed in above. In this case, the number is 3.
I’d like to also have it select the direct children of the original selector, #photo-gallery, so if I’ve got divs, list items, anchors tags, or whatever as direct children of #photo-gallery, those are the elements that nth-child(Xn) is applied to.
This is what I have with just basic jQuery, but I’m in the dark as to how to convert this into a plugin.
$('#photo-gallery div:nth-child(3n)').addClass("end-row-grid-item");
$('#photo-gallery div:nth-child(3n+1)').addClass("new-row-grid-item");
As far as the plugin goes, here is what I have so far…
(function($){
$.fn.extend({
//pass the options variable to the function
grid: function(options) {
//Set the default values, use comma to separate the settings, example:
var defaults = {
gridItems: 3
}
var options = $.extend(defaults, options);
return this.each(function() {
});
}
});
})(jQuery);
Like I said, I’m completely in the dark as to how to pass my selector and option in to complete the plugin.
Any help would be greatly, greatly appreciated!
If that’s really all the jQuery you need to make the effects, it might not be necessary to make a plugin… If you do want to, have a go with this:
This isn’t exactly the same as the code example you give. It only selects direct child nodes and it selects them whatever kind of element they are. This seems to be what you need.