Home > Visualforce, force.com Sites, jQuery > 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.