Using jQuery in a Visualforce Page

Source code:

<h2>Problem</h2>

You need to manipulate or animate client-side user interface elements on a Visualforce page using jQuery.

<h2>Solution</h2>
<p>
[url http://www.jquery.com]jQuery[/url] is an open source, actively supported, JavaScript library used to add client-side manipulation to HTML pages.  You can use it to do the same on your Visualforce pages.   jQuery is a cross-browser library designed to simplify the client-side scripting of HTML. Its syntax is designed to make it easier to navigate a document, select DOM elements, create animations, handle events, and develop Ajax applications. 
</p>
<p>
jQuery also provides capabilities for developers to create plugins on top of the JavaScript library. Using these facilities, you are able to create abstractions for low-level interaction and animation, advanced effects and high-level, theme-able widgets.   
</p>
As an example of using jQuery, we will create a dialog box for a list of records that displays a field value in a modal window.

<h3>Prerequisites</h3>
You will need to download the jQuery and jQuery UI libraries.  jQuery is the core library which offers DOM manipulation methods and jQuery UI is a higher level library which constructs widgets for use on your page.  From the jQuery UI site, you can [url http://www.jqueryui.com/download]download a zip[/url] tailored to the portions of the libraries you need.
<p>
Once you have the ZIP in hand, you’ll need to upload it as a static resource.  See [recipe creating-a-consistent-look-and-feel-with-static-resources] to see specifics on uploading and using a static resource with your Force.com application.
</p>
For the purposes of the code in this recipe, we’ll assume you’ve named the static resource “jQuery”.  To access jQuery in your Visualforce pages, you then need to include the libraries with something like this:

[code visualforce]
<apex:includeScript value="{!URLFOR($Resource.jQuery, '/js/jquery-1.4.2.min.js')}"  />
<apex:includeScript value="{!URLFOR($Resource.jQuery, '/js/jquery-ui-1.8.6.custom.min.js')}"  />
<apex:stylesheet value="{!URLFOR($Resource.jQuery, '/css/ui-lightness/jquery-ui-1.8.6.custom.css')}"  />
[/code]

<h3>About Using jQuery</h3>
<p>
To use jQuery within Force.com, you’ll need to make use of the jQuery.noConflict() function to reassign jQuery’s global variable to something which won’t conflict with any other libraries which may already be in use (including standard, native libraries used within Visualforce).  You’ll see an example of this in the code below.
</p>
<p>
With jQuery, you typically locate an element based on a CSS selector, attach it to an event or widget, and then perform a specific function.  Take this example:
</p>
[code visualforce]
$j = jQuery.noConflict();
$j("#phone").dialog({ autoOpen: false, modal: true, position: 'center'  });
[/code]
<p>
This instructs jQuery to find an element with the id of “phone”, create a dialog widget from it and set the initial parameters.
</p>
<p>
It’s a best practice to make use of the onReady event of jQuery to initialize your JavaScript.  This event will fire when DOM elements are ready, but before assets like images download.  So for example, you’d write something like this:
</p>
[code visualforce]
   $j(document).ready(function() {   /* …. Your actions …. */ } 
[/code]

<h2>A Code Sample</h2>
Here’s a complete code sample.  Assuming you’ve followed the pre-requisites, simply create a new Visualforce page with this source:

[code visualforce]
<apex:page showheader="false" standardController="Account" recordsetVar="accounts" >
<head>
<apex:includeScript value="{!URLFOR($Resource.jQuery, '/js/jquery-1.4.2.min.js')}"  />
<apex:includeScript value="{!URLFOR($Resource.jQuery, '/js/jquery-ui-1.8.6.custom.min.js')}"  />
<apex:stylesheet value="{!URLFOR($Resource.jQuery, '/css/ui-lightness/jquery-ui-1.8.6.custom.css')}"  />
<script>
   $j = jQuery.noConflict();
   $j(document).ready(function() {
    $j("#phone").dialog({ autoOpen: false, modal: true, position: 'center'  });
   });
   
   function showDialog(name, phone){
      $j("#phoneNumber").html(phone);
      $j("#phone").dialog("open");
      $j('#phone').dialog("option" , "title" , name);
      $j('#phone').dialog('option', 'position', 'center');
      return false;
   }
</script>
<style>
    .accountLink { color: blue; cursor: pointer; cursor: hand; }
</style>
</head>    
  
<body>

  <apex:dataList value="{!accounts}" var="account" id="theList">
        <a href="" class="accountLink" onclick="return showDialog('{!account.name}','{!account.Phone}')"><apex:outputText value="{!account.name}"/></a>
  </apex:dataList>
  
  <div id="phone" >
      <div style="float:left">Phone:</div><div id="phoneNumber"></div>
  </div>
  
</body>
</apex:page>
[/code]

<h2>Discussion</h2>
<p>
The HTML in the page creates a div with an id set to “phone”.  The JavaScript in the onReady jQuery function associates this div with a jQuery dialog widget, and sets it up to be a hidden modal window.
</p>
<p>
The showDialog() function, when called with a name and phone number, updates the phone number displayed within the div, sets its title, and opens the dialog making it visible and recentered.
</p>
<p>
So now you have a hidden div that can display data, and a function that will take this div and display it as a model dialog after adding data to it.  To tie it all together, we create a link around every account name that we display, that uses the onClick even to invoke the showDialog() function.  
</p>
<p>
jQuery takes care of the rest.  In fact, jQuery provides powerful DOM manipulation and widget creation in a minimal amount of code.  In this instance, the dialog box is draggable, modal (meaning the main page is not usable while the box is open), and can be closed with the escape key with only one line of code.  
</p>
<p>
Note we re-center the dialog box in the showDialog function in case Visualforce has updated the DOM during rendering, otherwise the box would have been centered by default as well.
</p>
<p>
In production, it would probably be best to have all the scripts and CSS in static resources - this example uses in-line code for easier cutting and pasting.
</p>
<h2>Resources</h2>
<ul>
<li>[url http://www.jquery.com]jQuery Home[/url] - this site provides everything you need on jQuery
<li>[recipe creating-a-consistent-look-and-feel-with-static-resources] demonstrates how to set up static resources
<li>The [url http://wiki.developerforce.com/index.php/Visualforce]Visualforce Resource Page[/url] has all you need on Visualforce
</ul>