A plugin adds a new method to jQuery. Thousands exist for sliders, date pickers, tables and more.
Popular plugins
| Plugin | Purpose |
|---|---|
| DataTables | search, sort and paginate tables |
| Select2 | searchable select boxes |
| jQuery Validation | form validation rules |
| Slick / Owl Carousel | sliders |
| jQuery UI | date picker, drag-and-drop, dialogs |
Using a plugin
- Load jQuery first
- Load the plugin's CSS and JS
- Call it:
$('#students').DataTable();
Write your own plugin
$.fn.highlight = function (options) {
const settings = $.extend({ color: 'yellow' }, options);
return this.css('background', settings.color);
};
$('p').highlight({ color: 'lightgreen' });
$.fnis where jQuery methods live$.extend()merges default options with the user's optionsreturn thiskeeps chaining working
Example
Example — A simple character-counter plugin
HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<textarea id="bio" rows="3" cols="40" placeholder="Short bio"></textarea>
<br><br>
<input id="title" size="40" placeholder="Post title">
<script>
$.fn.charCounter = function (options) {
const settings = $.extend({ max: 100, warnAt: 0.8 }, options);
return this.each(function () {
const $field = $(this).attr('maxlength', settings.max);
const $count = $('<div>').css({ fontSize: '13px', color: '#666' });
$field.after($count);
function update() {
const len = $field.val().length;
$count.text(len + ' / ' + settings.max)
.css('color', len >= settings.max * settings.warnAt ? 'crimson' : '#666');
}
$field.on('input', update);
update();
});
};
$(function () {
$('#bio').charCounter({ max: 150 });
$('#title').charCounter({ max: 60, warnAt: 0.9 });
});
</script>