Ask Questions and Find Answers
Important:
Ask is now read-only. You can review any existing questions and answers, but not add anything new.
But - don't panic! While ask is no more, we've replaced it with discuss - the new Liferay Discussion Forum! Read more here here or just visit the site here:
discuss.liferay.com
RE: References for using javascript in page fragments
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?
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.
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.
Copyright © 2025 Liferay, Inc
• Privacy Policy
Powered by Liferay™