Home > force.com Sites, jQuery, Visualforce > Setting up jQuery with salesforce.com

Setting up jQuery with salesforce.com

February 3rd, 2010

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.

mr-t_bigger

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.

uidown

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.

capture

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.

  1. Richard
    February 4th, 2010 at 09:39 | #1

    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.

  2. February 4th, 2010 at 11:21 | #2

    I don’t think I have one Visualforce page that doesn’t include one of those components :-P !

    Thanks for adding that.

  3. February 4th, 2010 at 12:49 | #3

    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

  4. February 4th, 2010 at 12:57 | #4

    Oh gosh, that’s why it’s bad to copy and paste markup/code!

    All fixed now.

  5. February 5th, 2010 at 01:37 | #5

    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.

  6. February 6th, 2010 at 21:20 | #6

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

  7. February 7th, 2010 at 13:46 | #7

    Jason, can’t wait for more jQuery and Salesforce.com posts. Keep them coming. I really need the help.

  8. March 16th, 2010 at 15:53 | #8

    Suppose I then use jQuery plugins (namely dataTables http://www.datatables.net/). Do I have to scour through that code and change $ to j$?

  9. March 17th, 2010 at 09:00 | #9

    @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/

  10. KiloJ
    April 9th, 2010 at 06:52 | #10

    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

  11. April 9th, 2010 at 07:34 | #11

    @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/

  12. Richard Tuttle
    April 9th, 2010 at 09:47 | #12

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

  13. Richard Tuttle
    April 9th, 2010 at 09:50 | #13

    @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’).

  14. KiloJ
    April 12th, 2010 at 02:25 | #14

    Guys, that’s fantastic information! Thank you so much – this will help me out greatly.

    Best,
    KJ

  15. Simona
    May 10th, 2010 at 14:05 | #15

    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

  16. KiloJ
    May 12th, 2010 at 07:49 | #16

    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

  17. KiloJ
    May 12th, 2010 at 07:51 | #17

    @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

  18. KiloJ
    May 12th, 2010 at 08:08 | #18

    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

  19. May 24th, 2010 at 10:25 | #19

    Jason – Thanks for the great post! Saved me a lot of trouble trying to fix conflicts with jQuery.

  20. October 7th, 2010 at 15:47 | #20

    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

  21. paul
    October 29th, 2010 at 08:29 | #21

    $(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”.

  22. paul
    October 29th, 2010 at 08:30 | #22

    $(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”.

  23. paul
    October 29th, 2010 at 08:34 | #23

    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”

  24. May 23rd, 2011 at 06:42 | #24

    OUCH! star in my eye!

    Hadouken!!!

    :)

  25. May 26th, 2011 at 06:48 | #25

    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.

  26. May 26th, 2011 at 08:10 | #26

    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.

  27. May 26th, 2011 at 08:14 | #27

    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 :P

  28. May 26th, 2011 at 08:16 | #28

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

  29. May 26th, 2011 at 08:25 | #29

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

  30. May 26th, 2011 at 08:31 | #30

    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.

  31. May 26th, 2011 at 08:45 | #31

    @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

  32. May 26th, 2011 at 08:46 | #32

    The last link on my previous comment should be…

    https://mydomain.secure.force.com/resource/zipResource/filename

  33. Sandeep
    August 26th, 2011 at 02:36 | #33

    Hi ,
    I am trying to login as a SFDC customer in an SFDC site . can u tell me how to do this using Jquery.