Yesterday I wrote a quick proof of concept that demonstrated jQuery code that would shorten a list of content to a set max and automatically add a 'Show More' link. The content was output by ColdFusion and could be any size. The JavaScript would check to see if there were more than 10 items and remove the ones after the 10th as well as adding the link to redisplay the content. This morning I quickly rewrote the code into a plugin (and took some of the advice I got on the last blog entry). Here is what I came up with.
First - let me begin by pointing you to the jQuery docs on plugin writing: Plugins/Authoring. This is a pretty straight forward guide to how plugins should be developed in jQuery. This was only my second plugin so I definitely had to reread this doc. I'll be honest and say that some of what the guide talks about is still a bit confusing to me - but I was able to understand enough to
(function($) {
$.fn.autoShortener = function(options) {
return this.each(
function() {
var settings = {
"length":10,
"message":"Show More"
};
if(options) $.extend(settings, options);
//get the children
var item = $(this);
var kids = item.children();
if(kids.length > settings.length) {
kids.slice(settings.length).hide();
$(this).append("<a href='' class='showMoreLink'>" + settings.message + "</a>");
$(".showMoreLink", item).click(function(e) {
item.children().show()
$(this).hide();
e.preventDefault();
});
}
}
);
};
})(jQuery);
For the most part this is the same logic as you saw in the blog entry yesterday - I just wrapped it in the proper format for plugins. I did make the length and message as options that you can override at runtime. Where things get real cool is on the front end. Check out the code now:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.autoshortener.js"></script>
<script>
$(document).ready(function() {
$(".list").autoShortener();
})
</script>
<ul id="list" class="list">
<cfloop index="x" from="1" to="25">
<cfoutput>
<li>Item #x#</li>
</cfoutput>
</cfloop>
</ul>
<div id="list2" class="list">
<cfloop index="x" from="1" to="25">
<cfoutput>
<div>Item #x#</div>
</cfoutput>
</cfloop>
</div>
That's a heck of a lot smaller. And if I want to override the options I could do something like this:
$("#list").autoShortener({length:8});
$("#list2").autoShortener({message:"More"});
You can see that version at the demo link below. Anyway - that's it. I'd love for this blog entry to be longer, more complex, etc., but jQuery just makes things to darn simple.