RE: References for using javascript in page fragments

John Cressman, modified 5 Years ago. Junior Member Posts: 39 Join Date: 8/15/17 Recent Posts
I am trying to create a dynamic page fragment and need to use some javascript.  I see the area in the fragment design screen where I can put javascript, but I can't seemed to reference it at all from inside the HTML area.  Nothing works - even when I call a simple function with an alert box.I looked through the site at the instructions to create fragments and found the javascript description EXTREMELY lacking.  Basically it says don't write alot of javascrript, call external JS Libraries.  Can anyone point me to some sample fragments where I see how they are calling the JS?
thumbnail
Christoph Rabel, modified 5 Years ago. Liferay Legend Posts: 1555 Join Date: 9/24/09 Recent Posts
Examples: You can look into the standard Liferay fragments, the basic components Slider or Tabs contain Javascript.
The Javascript code in the Javascript window is encapsulated inside of a function and therefore hidden. That's actually good, very good because the stuff in there would otherwise pollute the global namespace.
There are numerous tutorials out there explaining that practice, e.g.
https://www.tutorialspoint.com/javascript-encapsulation-using-anonymous-functions
There are two ways around this, one as Liferay does it, attaching events to objects/buttons and so on in that unnamed function. The other way, that also makes sense in some usecases, is to add your functions to the window object.
window.foo = function() { ... }
I would advise to use the first way, if possible.