Use jQuery + Plugins with Visualforce Pages
The jQuery library makes it much easier to create cross-browser functionality on any web page, and Salesforce Visualforce pages are no exception. Going one step further and include jQuery plugins in your pages as well for even more functionality and sparkles. But what do you do when you want to use a more recent version of jQuery, and your plugin is being reported as an undefined function in the console? To the rescue comes jQuery.noConflict(true);
.
First you will want to upload both jQuery and your plugin as Static Resources, or from a CDN if you prefer. For our purposes we will assume they are Static Resources called jQuery
and jQueryPlugin
. As soon as the javascript sources is includes – jQuery first followed by plugins – we need to make a call to noConflict()
to free up the $
resources. Using jQuery
as an alias is easy and logical.
Next we want to tell our code to run after the DOM of the page has loaded, so we wrap our code inside a function that is called by jQuery.ready()
. A neat trick here is to pass jQuery back into the callback function as $
, so your code will know the version of jQuery
you loaded and it’s attached plugins as the standard $
.
<!-- include static resources --> <apex:includeScript value="{!$Resource.jQuery}" /> <apex:includeScript value="{!$Resource.jQueryPlugin}" /> <script type="text/javascript"> // Alias to jQuery and free $ jQuery = $.noConflict(true); // Call jQuery.ready(), and alias jQuery back to $ by passing as an argument jQuery(document).ready(function($){ // use $.plugin() $('#container').plugin(); // attach events to DOM elements $('.button').on('click', function(){ alert('clicked!'); }); }); </script>