Setting up jQuery with salesforce.com
My posts have been lacking lately but in the next few weeks I plan on creating some super slick demos that mix jQuery and Force.com into a delicious concoction of wonderfulness. Before I do this I’d like to go over the basics of setting up jQuery to play nice with Force.com (or salesforce.com, all the same).
If all we need is jQuery, the first thing we need to do is download it here here: http://jquery.com/.
There will be two versions, one is considered production and the other development. These actually contain the same code but the production file removes all unnecessary spaces.
This smaller version allows the script to be downloaded quicker by users viewing the page and will provide a better user experience to those with less bandwidth.
jQuery lets you do a lot of sweet stuff, manipulate the DOM, change styles, basic animations, etc, but to provide an even richer user experience there is jQueryUI. This allows you to do all sorts of visual awesomeness with very little code.
jQueryUI can be downloaded here: http://jqueryui.com/download
When downloading jQueryUI you need to select theme (styles) and all the necessary components. For the sake of demoing and developing it makes sense download all of the components. Once again the reason to leave components out would be to decrease download size.
When you download jQueryUI you will be provided a zip with several files. This contains all sorts of demos and documentation but the only folders we care about are /css and /js. One very important thing to note when downloading jQueryUI is that it automatically downloads the regular jQuery (jQuery Core) to the /js folder.
Since we are going to upload these files as a .zip static resource to force.com I don’t even bother extracting the contents. Simply delete everything but the /js and /css folders. When this is done we should have a zip file called jquery-ui-1.7.2.custom.zip (or whatever the most current version is). Next we head off to Force.com.
In Force.com navigate to Setup>Develop>Static Resources and hit the New button. Make the name jquery and upload the zip file. If this resource is going to be used with force.com sites be sure Cache Control is set to public.
Now create a new visualforce page called jQueryTest. At the very top of the page we need to include the correct script and styles that jQuery has provided. We can do this with the following Visualforce tags:
With jQuery you will see a lot of examples including the $ symbol. This is basically a shortcut when calling jQuery functions. The problem is that force.com also includes a lot of javascript libraries that also may use this $ symbol as a shortcut and this can cause all sorts of problems. There is a simple fix as we can give jQuery it’s own special name.
var j$ = jQuery.noConflict();
Now where ever you would normally use $, use j$.
Finally we make sure it is all working correctly with this simple page. When you click on the link you should see a pop up alert. If you don’t something isn’t right so check for typos in the includeScript tags.
You can check out my working demo here: http://tehnrddemos-developer-edition.na7.force.com/jqueryTest
<apex:page > <apex:includeScript value="{!URLFOR($Resource.jquery, 'js/jquery-1.3.2.min.js')}"/> <apex:includeScript value="{!URLFOR($Resource.jquery, 'js/jquery-ui-1.7.2.custom.min.js')}"/> <apex:stylesheet value="{!URLFOR($Resource.jquery, 'css/ui-lightness/jquery-ui-1.7.2.custom.css')}"/> <script type="text/javascript"> var j$ = jQuery.noConflict(); j$(document).ready(function(){ j$("#ninjaLink").click(function() { alert("NINJA STAR TO FACE!!!!!"); }); }); </script> <a id="ninjaLink" href="">NINJA ATTACK!</a> </apex:page>
After this you are set to start making awesome sauce with jQuery and Force.com.

Very nice introduction to jQuery on SFDC. One thing I have found so far is that you only need to use the noConflict method when using VisualForce ajax type objects. Examples include commandLink, commandButton, actionSupport, actionStatus, etc. You could probably find an entire list by looking up a4j (ajax4jsf, the system VisualForce was built on). These particular tags use prototype to communicate the ajax between the controller and presentation layers.
I don’t think I have one Visualforce page that doesn’t include one of those components
!
Thanks for adding that.
Your first code example uses $Resource.configPricing…you might want to change that to $Resource.jquery like in your second code example to avoid confusion.
Otherwise, nice intro! Looking forward to seeing some of the cool things you build with jQuery and Force.com
Oh gosh, that’s why it’s bad to copy and paste markup/code!
All fixed now.
Now I have a ninja star in my eye, but the article was worth it
Haven’t encountered any conflict between Prototype and jQuery yet, but if (when) I do I’ll be able to sort it out chop-chop.
@Wes, I think it all depends on what jQuery functions you are calling. Sometimes I have had no issues while other times I get “function does not exist/defined” errors as the libraries are calling functions in the other that do not exist.
Jason, can’t wait for more jQuery and Salesforce.com posts. Keep them coming. I really need the help.
Suppose I then use jQuery plugins (namely dataTables http://www.datatables.net/). Do I have to scour through that code and change $ to j$?
@Scott Hemmeter
You shouldn’t need to make any changes to a plugin if they are written properly, and it looks like datatables is.
Plugins take special steps to make sure the $ alias does not interfere with other javascript libraries.
The example above is only one of many ways to prevent your own jquery scripts from interfering with other javascript libraries. More examples can be found here: http://api.jquery.com/jQuery.noConflict/
Hey. Do you know of any way to use a jquery selector to select say an ouput panel in a page?
For example if you have:
$(document).ready(function() {
$(‘panelTwo’).click(function() {…
});
This wont work because the id’s are prefixed with the name of the parent separated by a colon. You can see this if you view the source of the generated HTML of the VF page. I’ve no idea other than to use raw HTML in my code. Any ideas? Thanks
@KiloJ
This is possible but it requires a little extra work. The best way is to give all visualforce components id values and then when you look at the source you may see the panel that has an Id like “thePage:panel2″. Then you can do a selector like this:
var componentId = fixId( ‘{!$Component.thePage.panel2}’ );
$(componentId).click(function(){
//cool stuff
});
function fixId(myid) {
return ‘#’ + myid.replace(/(:|\.)/g,’\\\\$1′);
}
You could also put the fixId function straight into the jQuery selector but I seperated it out here to keep it simple.
Wes has put together a good post on this issue here: http://developinthecloud.wordpress.com/2010/02/17/visualforce-ids-in-jquery-selectors/
@KiloJ
What Jason said is exactly how I do this as well. Also lately I’ve been not using outputPanel and using an actual div instead. This is useful if you only need to use it with JavaScript and not necessarily any of the built in AJAX ie: rerendering that panel.
@KiloJ
Another note, you used the actual short name for jQuery. If you do any sort of rerendering, as mentioned in this article and my first comment you’ll end up with prototype (or is it extjs?) stealing the $ object. To fix this use the no conflict method Jason shows in his article and call jQuery as jQuery(‘selectorhere’).
Guys, that’s fantastic information! Thank you so much – this will help me out greatly.
Best,
KJ
It does not work on apex:inputField with date value.
Disabling a Datepicker field for this works, but when I added validation – validation is not working. Any idea?
Thanks a lot!
Simona
Hi again guys. I’ve noticed a really really frustrating error when trying to work with JQuery in Visualforce. I include the JQuery library in my visualforce page and I get the following Firefox error when viewing my visualforce page:
element.dispatchEvent is not a function
event.eventName=eventName;event.memo=m…nt.fireEvent(event.eventType,event);}
There is some sort of conflict between JQuery and the another script that is included by salesforce “https://na1.salesforce.com/faces/a4j/g/3_3_0.GAorg.ajax4jsf.javascript.PrototypeScript”. I have viewed the developer.force.com forums and found the following solution (http://community.salesforce.com/t5/Visualforce-Development/Not-able-to-Include-jQuery-JS-file-in-Visualforce-page/m-p/161635) albeit (You’ve guessed it!) it doesn’t work for me…
I only use “jQuery(…)” namespace. I don’t use ‘$’. I tried including the following code snippet directly after including the JQuery library in my visualforce page “jQuery.noConflict();” but this doesn’t work. I keep getting the error. I even went so far as to remove all the JQuery from my visualforce page, including the “include” declaration for the JQuery library and the problem persists! Surely one of you gurus must have come up against this error before? If so, can you post a correct solution to this really irritation problem!
Many thanks indeed
KJ
@KiloJ
Sorry, the last big of my previous post – I removed all the JQuery from my visualforce page (including the import for the JQuery library – apex:includeScript) and the problem goes away.
Thanks,
KJ
Gents, I’m such a dummy…
I followed the instructions at the top of the page to a tee this time and the problem is fixed!
Jason – congratulations for such a fantastic blog! It’s a great resource
Keep up the great work.
Regards
KJ
Jason – Thanks for the great post! Saved me a lot of trouble trying to fix conflicts with jQuery.
I realize that this is an old post, but great tutorial nonetheless. Using the noconflict() function is really important to remember. I love jQuery and Salesforce. Thanks
$(document).ready(function () {
$(‘body’).layout({ applyDefaultStyles: true });
});
Center
North
South
East
West
not able to embed this in visualforce page with . It works fine when showHeader=”false”.
$(document).ready(function () {
$(‘body’).layout({ applyDefaultStyles: true });
});
Center
North
South
East
West
not able to embed this in visualforce page with . It works fine when showHeader=”false”.
http://layout.jquery-dev.net/documentation.cfm#Example
cannot embed above example in the link ina visualforce page when showHeader=”true”
ex: .
it works fine when showHeader=”false”
OUCH! star in my eye!
Hadouken!!!
Just curious is there a reason you don’t use the google or microsoft CDN for jQuery? It’s much more likely the user would have it already downloaded from another site so it would already be cached and it’s one less thing for you to host and worry about. Google also hosts the themes and the UI package as well.
I never even realized you could use those CDNs over HTTPS, but you can @Kenji776 . Google’s requires an API key tied to a URL. For a Managed Package, this won’t work since there are so many URLs. For an in-house implementation, it will. It’ll be nice when they move the key to their newer API Console so it’s not URL dependent.
I haven’t had to use any keys or anything. The following URLs work just fine for me.
http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js
http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js
Maybe I’m not supposed to use them, but they’ve been doing the job so far
@Kenji776 Not sure why I didn’t think of that. I was reading the docs about using the AJAX loader. You are right. Also, the HTTPS version of those URLs work, which is nice for being in Salesforce.
@scott Kenji is referring to theses static CDN files: http://code.google.com/apis/libraries/devguide.html You don’t need an API key. If you are using the other google libraries that involve invoking their custom APIs…like for maps
, then you need the API key.
So why don’t I use the google/MS CDN? Well, salesforce.com actually has it’s own CDN through akamai I think, and static files on sites pages are served through this. Not sure about internal apps. If I was hosting the jquery files from some cheap $4 a month web server I would probably use a google CDN but salesforce already has an enterprise grade global CDN. Also, it would be very rare but google CDN could, and I think has, gone down before. If salesforce goes down my apps will be down anyway. If salesforces is up and google is down my apps are down. This risk, for me, isn’t worth the extra few milliseconds saved on page load….and only the first page load.
Also, in the past these CDN did not have a https option and you would get mixed content warnings in IE.
Jason, that is a really good point about multiple points of failure. I kind of mentally glossed over the fact that Salesforce has a high quality CDN. I’m used to developing stuff that will on some crummy in house server so anything I could offload was a bonus. Haven’t totally transitioned to coding in the cloud mentality yet I guess.
@jason @Kanji, you are both right
Within Salesforce, it’s probably safest to use Static Resources, but odds are both solutions will work since both Salesforce and Google do a pretty good job of staying online. For general webdev, using the CDNs is a great idea.
Also, did you know that by using Salesforce Sites, you have access to your Public Static Resources? Thus, you have a public CDN via Salesforce. The key is that Cache Control must be Public on the Resource.
http://mydomain.force.com/resource/resourceName
https://mydomain.secure.force.com/resource/resourceName
http://mydomain.force.com/resource/zipResource/filename
https://mydomain.secure.force.com/zipResource/filename
The last link on my previous comment should be…
https://mydomain.secure.force.com/resource/zipResource/filename
Hi ,
I am trying to login as a SFDC customer in an SFDC site . can u tell me how to do this using Jquery.