Saturday, January 3, 2015

Integrating jQuery with Visualforce


In this article, I will demonstrate how you can integrate jQuery with Visualforce Page. 
jQuery is the open-source JavaScript framework that Web developers use to solve basic app development problems across all browsers while opening the code to the public for community-driven development and support. 
jQuery can be used with Visualforce Page for user interface development. It will simplify the basic functionalities like DOM manipulation. The another biggest advantage of jQuery is that it is having a huge library of UI elements which you can use with Visualforce to make your user interface more interesting.
Below are the steps-
  • Download jQuery: You need to download jQuery. jQuery UI site is having a custom download builder which you can use to download jQuery. I prefer using custom download builder from jQuery UI website. Here is the link: jQuery UI
  • Add downloaded jQuery zip file as Static Resource: On your Salesforce Development org, go to Setup -> Build -> Develop -> Static Resources. Click on add and add the downloaded zip file. Give it a name. I have given the name jQuery1_11. (Don't worry, no naming convention here. You can choose any name).
  • Refer jQuery on your Visualforce Page: In this step, you need to refer jQuery on your Visualforce page and below is the way how you can do that.
    <apex:includeScript value="{!URLFOR($Resource.jQuery1_11, '/js/jquery-1.11.2.min.js')}"/>
    
  • The important step: Salesforce implement many javascript libraries. So the first major hurdle is to make sure that jQuery didn't interfere with any other javascript libraries that Salesforce has implemented. jQuery uses by default the global variable "$", so we are not supposed to use that. The simple solution for this is to use jQuery.noConflict() and to avoid using "$" for the jQuery syntax. Below is the code you need to write-
    var j$ = jQuery.noConflict();
    j$(document).ready(function(){
        //WRITE ALL YOUR FUNCTIONALITIES
    });
    
That's all. Below is a small example which you can use to verify whether you have configured Salesforce successfully or not.
Create a simple Visualforce page with the below code -
<apex:page >
    <apex:includeScript value="{!URLFOR($Resource.jQuery1_11, '/js/jquery-1.11.2.min.js')}"/>
    
     <script type="text/javascript">
        var j$ = jQuery.noConflict();
 
        j$(document).ready(function(){
            j$("#clickLink").click(function() {
                alert("WoW!! You hace configured jQuery successfully!!!!!");
            });
        });
     </script>        
 
     <a id="clickLink" href="">CLICK HERE TO TEST!</a>
 
</apex:page>
When you will run the Visualforce page, you should see the below screen -
Clicking on if you see the below screen, it indicates you have successfully configured jQuery with visualforce
Congrats!! If you have any feedback, please let me know. Thanks in advance.

0 comments:

Post a Comment