Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 56 ยท Plugins and Utilities

Using Plugins and jQuery UI

Choose and vet jQuery plugins, load scripts in the right order, use jQuery UI widgets like datepicker, sortable and dialog, apply noConflict and know when to pick alternatives.

Part of jQuery's long life comes from its ecosystem: thousands of plugins that add sliders, date pickers, tables, lightboxes and validators. Using one is easy in theory, because you load the script and call a method. In practice most problems come from a few avoidable mistakes: the wrong load order, an abandoned plugin, a clash with another library, or a heavy dependency for a feature the browser now includes.

This lesson shows how to add third-party plugins safely, how to use the best-known collection of widgets, jQuery UI, and how to decide whether you need a plugin at all. If you want to understand what happens inside a plugin, read Writing Your Own Plugin first.

Before you add a plugin

Maintained? Check the last release and open issues.
jQuery 3 ready? It must support your jQuery version.
Accessible? Keyboard and screen reader support.
Worth the weight? Compare size to the feature you need.
1 / 2

Choosing a plugin

A plugin becomes part of your page, so vet it the way you would any dependency.

  • Is it maintained? Look at the date of the last release and whether bugs get answered. A plugin abandoned in 2014 may break on jQuery 3, or carry known security problems.
  • Does it support your jQuery version? Some old plugins use APIs removed in jQuery 3 (see what changed in jQuery 3). Test with the console open; jQuery Migrate points at the culprits.
  • Is it accessible? A date picker that cannot be used with a keyboard excludes real users. Try tabbing through the demo.
  • How big is it, and what else does it pull in? A 100 KB plugin for a 5-line effect is a poor trade.
  • Is there a native alternative? <input type="date">, <dialog>, <details>, CSS scroll snapping and the Popover API now cover many old plugin jobs.
  • What does the licence say? MIT and similar licences are the safe default for commercial sites.

Loading order

Scripts run in the order they appear. A plugin attaches itself to jQuery.fn the moment it loads, so jQuery has to exist first, and your own code has to come last:

HTML
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
<script src="/js/some-plugin.js"></script>
<script src="/js/app.js"></script>

Never include jQuery twice. The second copy replaces window.jQuery, and plugins loaded before it are attached to the old copy and disappear from the new one, which produces the confusing error .somePlugin is not a function even though the plugin file did load. Also use defer consistently: deferred scripts keep their order relative to each other, but a plain script after a deferred one will run first.

Plugins usually come with a stylesheet. Load the CSS in the <head>, and pin versions everywhere so an update on the CDN cannot change behaviour on your site.

jQuery UI: widgets from the jQuery project

jQuery UI is a library of interactions, widgets and effects built on jQuery. Some of the commonly used pieces are:

  • Widgets: datepicker, dialog, tabs, accordion, autocomplete, slider, tooltip, progressbar, menu.
  • Interactions: draggable, droppable, resizable, sortable, selectable.
  • Effects: extra easings and effects such as highlight, shake and explode, plus colour animation.

You load the script, a theme stylesheet and then call a widget on an element. Every widget has the same API shape: .name(options) creates it, .name("option", key, value) reads or changes options, .name("method") calls methods such as open, close or destroy, and widgets trigger events named namechange or accept callbacks in the options.

JavaScript
$("#dialog").dialog({ modal: true, autoOpen: false, buttons: { Close: function () { $(this).dialog("close"); } } });
$("#dialog").dialog("open");
$("#dialog").dialog("destroy");

A word about its status: jQuery UI is a mature library that receives only occasional maintenance releases, and its design dates from before ES modules, CSS custom properties and native elements. It is perfectly reasonable on an existing jQuery site. For a new project, compare it with a native <dialog> element, <input type="date">, and focused libraries such as SortableJS for drag sorting.

Datepicker, sortable and dialog from the CDN

The order of the three tags matters here: the stylesheet in the head, then jQuery, then jQuery UI, then the script that uses them. Try swapping the jQuery UI and jQuery lines and the console will tell you that $.widget or datepicker cannot be found.

noConflict: sharing the page with other libraries

Other libraries, such as old versions of Prototype, also use $. jQuery.noConflict() gives the $ name back to whoever owned it before jQuery loaded, while leaving jQuery available. You can then use jQuery(...) directly, or put your code in a wrapper that receives jQuery as $:

JavaScript
jQuery.noConflict();

jQuery(function ($) {
  // here, $ is jQuery again
  $("#menu").addClass("ready");
});

Pass true (jQuery.noConflict(true)) to restore the previous jQuery as well, which makes it possible to run two jQuery versions on one page. This is a last resort when a legacy plugin needs jQuery 1.x. Each plugin must then be loaded while the version it wants is the current one, and kept inside its own wrapper.

noConflict hands $ back to another library

Searching for "jQuery plugin" turns up hundreds of names. These are ones you will keep meeting, and what each is for. Treat the list as a map, not a shopping list: check each project's current status before you adopt it, using the questions in Choosing a plugin.

Plugin Job Notes
AlertifyJS styled alerts, confirms, prompts and toast notifications replaces alert() and confirm(); does not need jQuery
Jcrop image cropping with a draggable selection box an old plugin; modern replacements are Cropper.js and Croppie
Highcharts interactive SVG charts commercial licence for most uses; it has had a jQuery wrapper ($("#c").highcharts(...)), but the direct Highcharts.chart() call is the current style
gmaps.js a friendlier wrapper around the Google Maps JavaScript API needs an API key; the underlying API is what you really learn, so many teams call it directly
CLNDR a calendar that renders from a template you write (Underscore or Lodash templates) good for event calendars; you supply the markup
table2excel exports an HTML table to an .xls file in the browser produces a spreadsheet-readable HTML file, not a true .xlsx; for real workbooks use SheetJS
jquery-timepicker a time picker dropdown for text inputs native <input type="time"> covers the simple case
Page Piling / Multiscroll (and fullPage.js) full-screen sections with snapping scroll, sometimes split into two columns look striking but fight users' scroll expectations and accessibility; CSS scroll-snap does the basic job
DataTables sortable, searchable tables see DataTables with jQuery

You can see the useful pattern with two of these, a notification plugin and a chart library, living next to jQuery. Neither needs jQuery to run; jQuery just wires them to the page:

Alertify notifications and a Highcharts chart from jQuery

When you add any of these, follow the loading-order rules above, and read the plugin's licence: some of the best-known (Highcharts, fullPage.js) are free only for non-commercial or limited use.

Checking whether a plugin is loaded

A plugin that failed to load (blocked CDN, wrong order, 404) shows up only when your code calls it: $(...).datepicker is not a function. You can check before you call. Instance plugins live on $.fn, utility plugins live on $ itself, so test the right object.

JavaScript
if (typeof $.fn.datepicker === "function") {
  $("#when").datepicker();
} else {
  console.warn("datepicker plugin is missing; using the native date input");
}

if ($.fn.jquery) { /* jQuery itself is present */ }
if (typeof $.myUtility === "function") { /* a utility plugin is present */ }
Detecting plugins

Use this check for optional enhancements. If the plugin is required, let the error happen early and loudly in development, rather than hiding it.

A word on maps

Several tutorials build "a simple map with jQuery". The map itself comes from a mapping service, not from jQuery: you load the provider's script (with an API key), create a map object in a div with an explicit height, and pass options such as a centre point, a zoom level and a map type (road map, satellite, terrain or hybrid). jQuery's only jobs are to find the div and to run the set-up after the document is ready. Because the services require keys and network access, these snippets cannot run here, so treat the shape below as read-only. Wrappers such as gmaps.js hide the same calls behind new GMaps({ div: "#map", lat: ..., lng: ... }).

JavaScript
$(function () {
  var map = new google.maps.Map($("#map")[0], {   // [0] gives the raw element
    center: { lat: 48.8584, lng: 2.2945 },
    zoom: 12,
    mapTypeId: "roadmap"                          // "satellite", "terrain", "hybrid"
  });
  $("#view").on("change", function () {
    map.setMapTypeId(this.value);                 // switch the type from a <select>
  });
});

Plugin hygiene

  • Initialise once. Calling .datepicker() twice on the same input is harmless for jQuery UI but not for every plugin. Keep set-up inside the document ready handler and run it once.
  • Destroy before removing. If you delete elements that have widgets, call the plugin's destroy method first (or use .remove(), which jQuery UI hooks into) so handlers and timers do not leak.
  • Initialise dynamic content after it exists. A plugin does not "watch" the DOM. For elements added later, call the plugin on them after inserting.
  • Do not edit vendor files. Wrap or override instead, so you can upgrade.
  • Self-host for production. A CDN is convenient, but pinned files in your own build avoid third-party downtime and let you add Subresource Integrity hashes.

Alternatives worth knowing

Before reaching for a plugin, check what the platform provides now: <dialog> for modals, <input type="date"> for dates, <details> for accordions, CSS position: sticky, scroll-snap for carousels and the IntersectionObserver API for lazy loading. For complex widgets, libraries that do one thing well (SortableJS for drag sorting, Flatpickr for dates, Choices.js or Tom Select for enhanced selects) are usually lighter than a general toolkit. They do not require jQuery, which means you can drop it later; the jQuery to modern JavaScript lesson shows the migration path.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You get "$(...).datepicker is not a function". What is the most likely cause?

    Plugins attach to jQuery.fn when they load. If jQuery UI is missing or loads before jQuery, the method does not exist when your code runs.
  2. 2. What does jQuery.noConflict() do?

    After noConflict(), $ points at its previous owner again; you use jQuery(...) or a wrapper function that receives jQuery as $.
  3. 3. Which of these is a good reason NOT to add a particular plugin?

    An abandoned plugin may break on current jQuery and can contain unpatched security issues.
  4. 4. What is the standard way to open a dialog that was created with $("#dlg").dialog({ autoOpen: false })?

    jQuery UI widgets take a method name as the first argument, so dialog("open") calls the open method.
  5. 5. Why should you avoid including jQuery twice on a page?

    Plugins register on the jQuery copy that existed when they loaded. A later copy starts clean without them.

Summary

  • Vet plugins for maintenance, jQuery 3 support, accessibility, size and licence, and prefer native features when they do the job.
  • Load order is jQuery, then plugins (and their CSS), then your code; never load jQuery twice.
  • jQuery UI offers widgets, interactions and effects with one API shape: .widget(options), .widget("method"), .widget("option", key, value).
  • jQuery.noConflict() returns $ to another library; use jQuery(function ($) { ... }) to keep $ inside your code.
  • Initialise once, destroy before removing, and self-host pinned files in production.

Now that you can build and use extensions, learn what has changed in the library itself in What Changed in jQuery 3.