Recipes by Category

App Distribution (2) Bundle logic, interface and services for distribution. App Logic (37) The Apex programming language, workflow and formulas for logic. Collaboration (6) The Salesforce Chatter collaboration platform. Database (29) Data persistence, reporting and analytics. Integration (33) Web Service APIs and toolkits for integration. Security (9) Platform, application and data security. Tools (4) Force.com tooling User Interface (36) Visualforce MVC and metadata-drive user interfaces. Web Sites (12) Public web sites and apps with optional user registration and login.
Beta Feedback
Cookbook Home » Using jQuery in a Visualforce Page

Using jQuery in a Visualforce Page

Post by joshbirk  (2011-02-04)

Status: Unverified
Level: intermediate

Problem

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

Solution

jQuery 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.

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.

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.

Prerequisites

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 download a zip tailored to the portions of the libraries you need.

Once you have the ZIP in hand, you’ll need to upload it as a static resource. See Creating a Consistent Look and Feel with Static Resources to see specifics on uploading and using a static resource with your Force.com application.

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:
<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')}"  />

About Using jQuery

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.

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:

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

This instructs jQuery to find an element with the id of “phone”, create a dialog widget from it and set the initial parameters.

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:

   $j(document).ready(function() {   /* …. Your actions …. */ } 

A Code Sample

Here’s a complete code sample. Assuming you’ve followed the pre-requisites, simply create a new Visualforce page with this source:
<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>

Discussion

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.

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.

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.

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.

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.

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.

Resources

Share

Recipe Activity - Please Log in to write a comment

 I have been having a problem trying to get this code to work in visualforce
 

 

by Sean Parker  (2014-02-26)

FYI - good article that shows how to get the Apex ID for jQuery - http://shivasoft.in/blog/others/tips/handling-colon-in-element-id-in-jquery-visualforce-problem/

by Diego Montoya  (2012-09-27)

Is there a good example of using of how to escape the colons from the component Id?  

by Diego Montoya  (2012-09-27)

how to add Visualforce Page to Visual work Flow

by Krishna Priya Chepuri  (2011-12-14)

how to use calendar.js in a visual force page??
i have a calendar.js  file zipped and added as a static resource in my developer account.

by KALLURI SURESH  (2011-11-24)

Very helpful recipe.. i was looking for it. thanks

by Tabraiz Feham  (2011-07-17)

Please make sure that you set proper reference to js file names by looking at your current downloaded zip file extract. Nice post Regards Vishwas

voted as verified by vkarhade03032010  (2011-07-11)

Nice work!!!

voted as verified by Prathamesh Joshi  (2011-06-10)

try using the id's like this

function jq(myid) 
    { 
    return '#' + myid.replace(/(:|\.)/g,'\\\\$1');
    }
    j$(jq('{!$component.id}')) or the j$(jq('thepage:theblock:thetable'))

it works for salesforce ids.

by siddharatha nagavarapu  (2011-05-16)

Great recipe

by Ping Pong  (2011-05-10)

Using apex components in jquery on a visualforce page is always tricky since you want to escape the colons form the component id. I always see the exaple of jquery on a visualforce page with simple HTML components and not the apex ones.

by Osama Nasir  (2011-02-18)

X

Vote to Verify a Recipe

Verifying a recipe is a way to give feedback to others and broaden your own understanding of the capabilities on Force.com. When you verify a recipe, please make sure the code runs, and the functionality solves the articulated problem as expected.

Please make sure:
  • All the necessary pieces are mentioned
  • You have tested the recipe in practice
  • Have sent any suggestions for improvements to the author

Please Log in to verify a recipe

You have voted to verify this recipe.