2

I'm known to using External JS library in Lightning Component but is there any way I can put a normal JS function like the on I would put in normal Visualforce such as function toggleDiv() {...}?

I'm getting error when I try to add <script>...</script> tag to Lightning Component.

2

Script tag blocks are not allowed in Lightning Components as they are a security risk. You should put your code in the controller, helper, or renderer as appropriate.

  • Can you give me a small sample of sort, in which I can call a JS function from controller or helper or renderer into each other? IN all the samples or documentation I encountered I noticed that we can use Controller functions in some predefined syntax and are clickable from buttons etc. I guess I'm confusing a lot :-) ... I simply want to have a JS function that will find an element via a class using jQuery and operate on it to hide or show it (like a collapsible/expandable section) ... – VarunC Sep 23 '15 at 17:48
1

You can add a "normal" Javascript Function to your helper file. For example if you are on a component named "foo". You can create a fooHelper.js file and add your code:

toggleDiv : function(div){
    $A.util.toggleClass(div, 'classToToggle');//you don't have to use jQuery :)
}

And then call this inside your controller (fooController.js):

bar : function(component, event, helper){
    helper.toggleDiv(component.find('myDiv').getElement());
}
  • is there a way I can call a Helper function inside another helper function? Because I tried calling the function defined in helper.js and it is returning that function is not defined error in js console. – VarunC Oct 9 '15 at 18:07
  • I believe you can use this.functionName(). See this : developer.salesforce.com/forums/?id=906F00000005FHGIA2 – Moshe Karmel Oct 9 '15 at 18:54
  • Thanks for comment here @moshe .. but I tried that and it worked fine but when I sue it to calla function recursively it freezes the browser window. Don't know why, same function runs fine in normal browser JS or visualforce page. My function looks like this: startClock : function() { setTimeout( this.startClock() , 1000); } also if I put Double Quotes around the function call, it does not recognize the function at all and throws error that function is not defined for this - startClock : function() { setTimeout( "this.startClock()" , 1000); } – VarunC Oct 9 '15 at 19:03
  • Hmmm interesting, maybe ask this as it's own question. Also it seems like startClock is recursively calling itself. Is this what you are trying to do? – Moshe Karmel Oct 9 '15 at 19:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.