Friday, 20 January 2017

How to use jQuery in Lightning


Below are the steps with simple example on how to use jquery in Lightning component.

1) Import the jquery library as static resource in salesforce

2) Include below markup in the lightning component.

<ltng:require scripts="/resource/jquery/" afterScriptsLoaded="{!c.doInit1}"/>

Please note: I have named the static jquery library has 'jquery' that is why in the above markup for scripts attribute i have given value as /resource/jquery/. Name must be given as per thee static resource name given in step1

3) Write the below simple jquery code in your component js file for testing the jquery call.

  doInit1 : function(component, event, helper) {

      console.log('*************** Inside do Init1 Method *****************')
        
      jQuery("document").ready(function(){
          
         console.log('Inside jquery'); 
          
          alert("Jquery");
          
      });
        
}

4) When you execute your component, you should verify the browser console and alert should be popped up if jquery is successfully invoked.

Import point to note :

1) Either jQuery can be used to refer jquery code or $ can also be used in component js file. for example look into code given below

 var opts1 = {
                    "class1": "optionClass1",
                    "class2": "optionClass1",
                    "class3": "optionClass1"
                  };
         
                
$.each(opts1,function(key,value){
              
             console.log('Key is' + key);
              
});

2) In the markup for lightning component which includes the js script. afterScriptLoaded is not mandatory.


No comments:

Post a Comment