Developing Apps with jQuery

jQuery is a popular open-source JavaScript framework that Web developers use to solve basic app development problems across all browsers while opening the code to the public for community-driven development and support. jQuery's design lets developers extend the core libraries with new projects and plugins to add new features and functionality.

For Force.com developers, jQuery simplifies user interface development by simplifying basic functions like DOM manipulations and giving access to a large library of UI elements and techniques for technologies including AJAX and mobile devices. jQuery can be used with any Visualforce or Site.com page.

Understanding Key jQuery Projects

Jquery-project-logo.jpg

The jQuery Foundation manages the main jQuery projects, of which three are commonly used by developers to build interfaces with JavaScript.

jQuery

Jquery-logo.jpg

jQuery itself is the core jQuery library which handles basic functionality like DOM manipulation and finding specific nodes within a page. Using jQuery, it becomes simple to find and control elements on the page. For instance, jQuery (in this example, defined as "j$ by noConlflict()") can find an element or array of elements by looking for specific CSS selectors, and then hide all the elements found by the selector in a single method call. Here, we'll hide all elements with the class "accountDiv":

  j$ = jQuery.noConflict();
  j$('.accountDiv').hide();

The selectors work with the same naming convention as CSS, so to find an element with an id of accountDiv instead, you would send jQuery "#accountDiv". jQuery often works by finding elements, attaching an event to those elements, and then defining a function for that event. In the following example, all of the elements found by our CSS selector will show or hide when clicked — "this" refers to the specific element being clicked and "toggle()" will flip the visibility of the element.

  j$ = jQuery.noConflict();
  j$('.accountDiv').click(function () {
    $(this).toggle();
  });

Note: In this example, we make a reference to the main jQuery function with the "noConflict()" method of the library, which removes any conflict between jQuery and other libraries using "$" as their default global object name (as can be the case with Visualforce). More detail on this later.

A common event to use with jQuery is the document object's ready event:

   j$ = jQuery.noConflict();
   j$(document).ready(function() {
     //initialize our interface
    });

The browser fires "ready" after fully loading the DOM, but before all assets (like images) are done loading. This makes it safe to go ahead and start referencing elements on the page without waiting for large assets to download, making for a faster loading UI.

jQuery UI

jQuery UI is a user interface library, based on jQuery, which adds interface elements like tabs, data tables, and modal windows. With jQuery UI, it becomes quick and easy to extend your interface.


Jquery-ui.jpg


Unlike the jQuery core project, jQuery UI commonly attaches an actual widget to elements found via CSS selection. Here we'll create a modal window out of the div with the specific ID:

 $j("#popupDiv").dialog({ autoOpen: false, modal: true, position: 'center'  });

jQuery Mobile

jQuery Mobile is a jQuery-based mobile framework that lets you easily create mobile friendly interfaces.


Jquery-mobile-devices.png


Mobile development is simpler with jQuery Mobile because you can define different mobile screens with multiple divs easily, as opposed to creating multiple HTML pages. Combined with mobile friendly JavaScript and CSS, jQuery Mobile makes the rapid development of mobile screens a snap.


For instance, by defining a div as follows, jQuery Mobile already knows it is a page:

<div data-role="page" data-theme="b" id="detailpage">

</div>

Now you can define the following link:

<a href="#detailpage">Go to Detail</a>

When a user clicks on the link, jQuery Mobile updates the interface with the referenced div in a style similar to going to a brand new page. The construction of one HTML page with multiple divs that make up multiple mobile pages makes it easy to develop mobile friendly apps. At the same time, this approach helps reduce the number of server requests — making the interface perform faster while on the road as well.

Integrating jQuery with Visualforce

Visualforce supports any client-side web technology, and jQuery is no different. However, there are a few things to be aware of about jQuery/Visualforce integration before moving ahead.

Placing jQuery on Your Visualforce Page

A Visualforce page needs to reference the JavaScript and CSS for the jQuery project and plugins it is trying to utilize. For the main jQuery libraries, the page can reference one of the many CDN's hosting jQuery. For example:

 <apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" />

Or you can include it as a static resource once you load it into your Force.com org:

 <apex:includeScript value="{!URLFOR($Resource.jQuery, '/js/jquery-1.7.2.min.js')}"  />

To include other projects and plugins, add the specific references in the proper order (with jQuery being referenced first).

Using jQuery's No Conflict Mode with Visualforce

There are other libraries that make use of the same global variable name ("$") that jQuery uses by default — Force.com's default interface commonly includes at least one such library. Considering this issue, combining jQuery with Force.com interfaces can cause a conflict on the client side. There's an easy solution, however:

 j$ = jQuery.noConflict();
 j$(document).ready(function() {
    //code when page is ready 
    });

And now the document's ready function can be set up using "j$" instead of "$" without the former conflict between libraries.

Referencing Visualforce Components with jQuery

Finding specific HTML nodes within the dynamically generated content of Visualforce can be a little tricky, because Visualforce prepends components with its own variables. For instance, consider this Apex repeater:

<apex:dataList value="{!accounts}" var="account" id="theList">

        <a class="accounts" id="list-{!account.id}" href="/{!account.id}">
         <apex:outputText value="{!account.name}"/>
        </a>

 </apex:dataList>

When Force.com renders this component, this dataList has an id of "j_id0:theList". So how would your page be able to select this with jQuery? Fortunately, jQuery makes it easy to work with using partial selectors. For instance, to find an element with the above dynamically generated ID, you could use the following:

j$('[id*=theList]')

Another trick of integrating Visualforce with jQuery is the ability to reference non-standard data attributes. For example, when you want to send some data about an account on a specific link when a user clicks the link, you could put the following on the link:

<a href="" class="accountLink" data-account="{!account.name}|{!account.Phone}"><apex:outputText value="{!account.name}"/></a>

Now you can create a click event that references that data directly:

j$(".accountLink").click(function() { 
        data = j$(this).data('account').split('|');
        showDialog(data[0],data[1]);
    });

Note that the data method of jQuery core is a very powerful feature here with several options for manipulating data related to your DOM structure.

Using JavaScript Remoting

JavaScript remoting is a feature of the Force.com platform that lets you integrate Apex controller methods directly with JavaScript functions. Without JavaScript remoting, you would have to use traditional Apex form components and manage associated view state (see An Introduction to Visualforce View State for more information about view state).

To set up remoting methods on the controller side, use the RemoteAction annotation:

public class MyCustomController { 

public MyCustomController() {}

@RemoteAction
    public static String createContact(string FirstName, string LastName) {
       Contact c = new Contact(FirstName=FirstName,LastName=LastName);
       insert c;
       return c.Id; 
       
    }

}

Now, from a Visualforce page that references a RemoteAction controller method, JavaScript can call the method by utilizing the name of the controller as an object:

<apex:page Controller="MyCustomController">
 <script>
   j$ = jQuery.noConflict();
   j$(document).ready(function() {
        j$(".createContact").click(function() { 
           MyCustomController.createContact(j$('#firstName').val(),j$('#lastName').val(),handleContactCreate);
        });
  );

  function handleContactCreate(result,event) {
         if(event.type == 'exception') {
              alert(event.message);
          } else {
           	alert('A contact was created with the ID: '+result);
          }
      }
  }
 </script>
</apex:page>

The function call in JavaScript passes values for the RemoteAction method parameters, followed by the name of a JavaScript handler function that can receive the results as well as information about the event (such as if there was an error). On the client side, functions are called asynchronously, and on the server, the methods are static.

Common jQuery Components, Plugins, and Frameworks

What follows is a short list of components, plugins, and frameworks that Force.com developers may find useful with jQuery. It is far on the other end from exhaustive, as jQuery has a massive list of choices when it comes to such material. However, these examples may provide some examples for solving common use case scenarios.

Mobile Components for Visualforce

The Mobile Components For Visualforce is an open source library of Visualforce components that makes combining HTML5 and jQuery Mobile easy for developing mobile friendly Visualforce pages. Designed to work with the Mobile SDK, Mobile Components is a great starting place for anyone looking to create their mobile application using HTML5 and JavaScript. You an even extend it to build your own custom components and contribute such components to the open source project on Github.

DataGrids

DataGrids are one of the most popular type of plugins for jQuery, allowing you to create dynamic and custom tables of data for your pages. Here are three of the most popular:

jQuery Tools

jQuery Tools provides an alternate set of UI components for use with jQuery with a wide range of options including overlays, modal popups, form input widgets and validation feedback, and tabs. It is a separate framework from jQuery UI and does not require jQuery UI to operate.

MVC/Template Frameworks

JavaScript has become increasingly important in structuring pages and interfaces dynamically. More than simply modifying DOM structures, these projects allow for generating pages based on data structures directly and mimic similar behavior often associated with server-side technologies like PHP and ASP.

Related jQuery Resources


About the Author

Josh Birk is a Developer Evangelist for Salesforce.com. In the 90's he wrote a cross-browser JavaScript library called Glimmer which he is quite happy not to need anymore. When not travelling from conferences to workshops to meetups, he can be found in a small study in Chicago - or anytime at joshbirk on twitter.