Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Building Your First jQuery Plugin

DZone's Guide to

Building Your First jQuery Plugin

· Web Dev Zone
Free Resource

Try RAD Studio for FREE!  It’s the fastest way to develop cross-platform Native Apps with flexible Cloud services and broad IoT connectivity. Start Your Trial Today!

So you were out on your quest to find the answer to life, the universe, and everything, when blam, you found jQuery. Yes, I know, you were expecting 42, but too all of our surprise, it was jQuery. So what's next? Build your own plugin!

While some are intimidated by the thought of creating their own plugin, the truth is that jQuery is built with an infinitely friendly plugin architecture. If you've gotten comfortable with the basics of jQuery coding, then you're certainly ready to develop your own plugin. This tutorial will take you step by step through creating your very own truncation plugin. Say, for example, you have a "tip of the day" widget on your home page. This plugin will let you truncate it to a specified length, with a link to expand it to view it's full content. The following image demonstrates a truncated piece of text:

The source article (opens new window) for this posting has working examples of this plugin.

Note that if JavaScript is disabled (or not supported) the content will simply display in its entirety.

You ready? Let's dig in...

Step 1

The first step is to extend the actual jQuery object with the function that we wish to add. In our case, we wish to add "truncation" functionality. So here's where to start: create a jquery.truncate.js file and save it with the following code:

$.fn.truncate = function(options) {
return this.each(function() {
});
};

Now you may have heard that plugin developers should not user the $ alias, as this can result in conflicts with other libraries. This is only partially true. The following snippet is the same as the one above, except that we pass jQuery into the function, allowing us to use an alias we want. We'll stick with $.

(function($){
$.fn.truncate = function() {
return this.each(function() {
});
};
})(jQuery);

Step 2

Before we go any further, let's create a simple test page that we can use to test our plugin. Create a page and call it whatever_you_want.html. Insert the following code. As you can see I placed both the jQuery library and the plugin inside a folder named js. Note that we are already invoking our plugin in this snippet, although we have not yet coded any behavior.

<html>
<head>
<title>Truncation Plugin Test</title>
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jquery.truncate.js" type="text/javascript"></script>

<script type="text/javascript">
$().ready(function() {
$('.tip').truncate();
});
</script>

</head>
<body>
<div class="tip" style="width:200px;background-color:#ccc;padding:10px;">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam fringilla, purus a ultrices blandit,
odio ante scelerisque neque, vitae imperdiet odio velit ac nisl. Sed tortor metus, placerat condimentum,
feugiat in, feugiat adipiscing, mi. Donec pulvinar sem vitae leo. Vestibulum eget lectus et ligula hendrerit
pharetra. Sed porta justo ac nisl. Aliquam nisi erat, pellentesque sed, sagittis eu, fringilla sit amet,
dolor. Nam ac mi. Pellentesque pede purus, mattis aliquet, semper nec, cursus a, orci. Duis bibendum nibh
ac massa. Integer eu tortor. Aenean convallis quam at nunc. Nunc mollis tincidunt nisi. Suspendisse mauris
odio, iaculis ut, feugiat vitae, ultrices in, tortor. Quisque at elit. In hac habitasse platea dictumst.
</div>
</body>
</html>

Step 3

The next thing we want to do is provide a mechanism for the user to customize the plugin. While we want to make the plugin as flexible as possible, we should also provide defaults so that the user isn't forced into providing a long list of parameters. We can easily do this using jQuery's extend method. Update your plugin to match the following:

(function($){
$.fn.truncate = function(options) {
var defaults = {
length: 300,
minTrail: 20,
moreText: "more",
lessText: "less",
ellipsisText: "..."
};
var options = $.extend(defaults, options);

return this.each(function() {
});
};
})(jQuery);

For now we won't override any of the defaults in our test page, but we'll demonstrate this later.

Step 4

So that takes care of all the preliminary considerations. Let's get to coding the plugin's functionality. As you've already seen, the plugin is returning this.each(...). This line will execute the contained anonymous function on each item in the jQuery array. So, if for example we called $('p').truncate(), the code we're about to write would execute on every p tag.

Since I'm assuming a comfortable understanding of jQuery, I won't explain in detail how the function's code actually works. If anything in the code is not obvious, you should refer to the documentation or ask a question in the comments. To complete your plugin, update it to match the following:

(function($){
$.fn.truncate = function(options) {
var defaults = {
length: 300,
minTrail: 20,
moreText: "more",
lessText: "less",
ellipsisText: "..."
};
var options = $.extend(defaults, options);

return this.each(function() {
obj = $(this);
var body = obj.html();

if(body.length > options.length + options.minTrail) {
var splitLocation = body.indexOf(' ', options.length);
if(splitLocation != -1) {
// truncate tip
var splitLocation = body.indexOf(' ', options.length);
var str1 = body.substring(0, splitLocation);
var str2 = body.substring(splitLocation, body.length - 1);
obj.html(str1 + '<span class="truncate_ellipsis">' + options.ellipsisText +
'</span>' + '<span class="truncate_more">' + str2 + '</span>');
obj.find('.truncate_more').css("display", "none");

// insert more link
obj.append(
'<div class="clearboth">' +
'<a href="#" class="truncate_more_link">' + options.moreText + '</a>' +
'</div>'
);

// set onclick event for more/less link
var moreLink = $('.truncate_more_link', obj);
var moreContent = $('.truncate_more', obj);
var ellipsis = $('.truncate_ellipsis', obj);
moreLink.click(function() {
if(moreLink.text() == options.moreText) {
moreContent.show('normal');
moreLink.text(options.lessText);
ellipsis.css("display", "none");
} else {
moreContent.hide('normal');
moreLink.text(options.moreText);
ellipsis.css("display", "inline");
}
return false;
});
}
} // end if
});
};
})(jQuery);

You'll notice that whenever I needed to select an element within the plugin, I always used obj as my context (e.g., moreLink = $('.truncate_more_link', obj)). This is necessary to constrain any selections to the current truncated element. Without setting the context like this, you will get unpredictable results.

So that's it - your first jQuery plugin! We're not quite finished though, since I promised we'd demonstrate overriding the default options. In the following example, every option has been over ridden, although it is perfectly valid to override fewer. Just replace the script in your test page with this:

$().ready(function() {
$('.tip').truncate( {
length: 120,
minTrail: 10,
moreText: 'show more',
lessText: 'show less',
ellipsisText: " [there's more...]"
});
});

This code will give you something like this:

Well... I hope you found this helpful. If you have any questions beyond what I've explained, please just ask in the comments. Please note that the plugin developed in this tutorial has evolved into the jTruncate plugin that can be found in the jQuery plugin repository, or here at my blog. Thanks for reading!

Get Your Apps to Customers 5X Faster with RAD Studio. Brought to you in partnership with Embarcadero.

Topics:

Published at DZone with permission of Jeremy Martin. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}