Archive

Archive for the ‘jQuery’ Category

Add Slider to a Visualforce Page with jQuery

February 16th, 2010 17 comments

A while back Jeff Douglas posted on his blog how to embed a Flex slider into a visualforce page. This is pretty slick and can be really useful, but I’m not a really a fan of Flex (I’ll post about that later) so today let’s look at doing the same thing a little different.

Instead of using Flex to build the slider I will show you how to do this with javascript. This requires less code and I feel it is easier to implement.

We are going to add a super nifty ultra slick slider with only 16 lines of javascript code.

You can check out the working demo by clicking here..

Below is all of the Visualforce markup, jQuery script, and Apex code. I’ve added most of my notes on what everything does in the comments but feel free to let me know if something isn’t clear or if you have any questions.

The one piece that may jump out at you is why I am using the native javascript getElementbyId method when assigning values to the inputFields. It is because these fields are apex:inputFields and they are given a funky Id that looks like this:

page:form:block:values:budgetHigh

The auto generation of these ids is cool as it prevents duplicate Ids but the semi-colons in the Id wreak havoc on jQuery. Using regular javascript wasn’t that much more work and there were no issues.

<apex:page standardController="Demo__c" id="page" extensions="slider">
 
    <!-- Here we incldued the necessary jquery javascript and css files -->
    <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">    
        //This will load as soon as the page is ready and will setup our slider
        $(document).ready(function(){
            $("#slider-range").slider({ //This line creates a slider on the DIV specified, options are passed arguments, comma separated below
                range: true, //This give the slider and top and bottom
                min: 0, //Min value for slider
                max: 1000, //Max value for slider
                values: ['{!FlOOR(Demo__c.Budget_Low__c)}', '{!FLOOR(Demo__c.Budget_High__c)}'], //Start values for the slider
                slide: function(event, ui){ //This function executes every time slider is moved and applies the slider values to the input fields as well as the output below the slider
                    document.getElementById('{!$Component.page.form.block.values.budgetLow}').value = ui.values[0];
                    document.getElementById('{!$Component.page.form.block.values.budgetHigh}').value = ui.values[1];
                    $("#amountValue").html('$' + ui.values[0] + 'K - $' + ui.values[1] + 'K');
                }
            });
 
            //This line executes only once right after the page is loaded and after the slider is initialized. It creates the "$273K - $611K" text on load
            $("#amountValue").html('$' + $("#slider-range").slider("values", 0) + 'K - $' + $("#slider-range").slider("values", 1) + 'K');
        });
    </script>
 
    <apex:form id="form">
        <apex:pageBlock mode="edit" id="block">
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!save}" />
            </apex:pageBlockButtons>
 
            <apex:pageBlockSection >
                <apex:outputField value="{!Demo__c.Name}"/>
            </apex:pageBlockSection>
 
            <apex:pageBlockSection title="Budget Info" columns="2">
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="Budget Range"/>
                    <apex:pageBlockSectionItem >
                        <!-- This is where our slider will be -->
                        <div id="slider-range" style="font-size: 90%; margin-top: 0.5em;"></div>
                        <div id="amountValue" style="text-align: center;"></div>
                    </apex:pageBlockSectionItem>
                </apex:pageBlockSectionItem>
            </apex:pageBlockSection>
 
            <apex:pageBlockSection columns="1" id="values">
                <!-- You could make these fields apex:inputHidden and then use only the slider -->
                <apex:inputField value="{!Demo__c.Budget_Low__c}" id="budgetLow" />       
                <apex:inputField value="{!Demo__c.Budget_High__c}" id="budgetHigh"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
 
</apex:page>

Very simple extension. Simply to override the save and prevent demo from returning to record.

public class slider {
 
    Demo__c d;        
 
    public slider(ApexPages.StandardController controller){        
        d = (Demo__c)controller.getRecord();             
    }        
 
    public void save(){        
        update d;        
    }
}
Categories: Visualforce, jQuery

Setting up jQuery with salesforce.com

February 3rd, 2010 7 comments

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:

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

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.