Adding jQuery To Your Force.com Application | Salesforce Developers Blog

jQuery has been a game changer for many JavaScript developers, myself included.  I once actively avoided most pre-built libraries for fear that somewhere after adopting them I would run into some conflict or limitation that would either slow or completely unravel any efficiency I got from using it in the first place.  jQuery, however, rests comfortably in a new breed of libraries with massive amounts of community support – especially in terms of testing, additions and examples.

At Dreamforce, I had the distinct pleasure of presenting with Jason Venable, AKA TehNrd on twitter and the blogosphere, on adding jQuery to Salesforce.  If you’re the type that likes to jump to the end … you can download the package of the demo org which includes the code samples or even view the video of the session.

The quick steps to getting started are simple:

1. Download jQuery
More specifically if you head over to the jQuery UI site, they have a great custom download builder, if you want to only get what you need.

2. Add jQuery as a Static Resource
ZIP in hand, you can include jQuery as a static resource, which will allow you to include the scripts easily within Visualforce pages.

3. Include jQuery scripts and set jQuery noConflict
Now that jQuery is accessible, simply add the reference to the jQuery libraries you need and then make sure to set jQuery noConflict.  Here's an example:

   <script src="{!URLFOR($Resource.jQueryFiles, 'js/jquery-1.4.4.min.js')}"/>
   <script src="{!URLFOR($Resource.jQueryFiles, 'js/jquery-ui-1.8.7.custom.min.js')}"/>
   <apex:stylesheet value="{!URLFOR($Resource.jQueryFiles, 'css/ui-lightness/jquery-ui-1.8.7.custom.css')}"/>
   
   <script type="text/javascript">
       var j$ = jQuery.noConflict();
       
       j$(document).ready(function(){
           //document ready code
       });
    </script>

Using jQuery.noConflict() gets around the problem that other, natively included, libraries also use the $ variable to refer to global functions.  In this example, you would refer to j$ instead and j$ will refer specifically to the jQuery functionality.

And that’s it – three easy steps and your Visualforce is ready for jQuery goodness.  Check out the jQuery site for examples if you need some starting points, or Jason’s demo package for specifics with using it with Salesforce.

 

Stay up to date with the latest news from the Salesforce Developers Blog

Subscribe