How to embed and invoke javascript script on RichFaces / JSF page

I was looking for a way to embed and call javascript functions on JSF pages. I also use RichFaces.

To define the function, it looks like I can do this with a cross browser:

<a4j:outputPanel ajaxRendered="true"> <f:verbatim> <script type="text/javascript"> function datum() { alert("hi"); } </script> </f:verbatim> </a4j:outputPanel> 

but I'm not sure how I can call this function when the page loads, so the text that it returns is embedded in h:outputPanel . The plan is to have js clock embedded in the page that is served to the client. Note. I do not use the body tag, I use facelets ui:composition , f:view (core) and RF RI rich:page .

thanks

+4
source share
1 answer

No matter what types of server tags you use, by the time your page hits the browser, all of this is just HTML. (At least it would be better, or it won’t work.) What you need to do is organize the code that is called by the "load" event handler. There are various ways to do this, but the simplest would be the following:

  <f:verbatim> <script type="text/javascript"> window.onload = function() { alert("hi"); } </script> </f:verbatim> 

Now, to initialize another part of the page, what’s ending in HTML is important again. You want some HTML container (a <div> or something depending on the design of your page), and you want it to have a unique id attribute. Then your Javascript can use "id" to find the element and set its contents:

  var elem = document.getElementById("whatever"); elem.innerHTML = // ... whatever ; 

You are likely to do this inside the "load" function.

Also, if you use Facelets instead of JSP, which is an XML-based presentation technology, you will need to add CDATA XML section separators if your JavaScript contains // comments or literals such as <,>, & &, etc. . Here's an example with XML CDATA delimiters:

  <f:verbatim> <script type="text/javascript"> //<![CDATA[ //Comments won't show error now. window.onload = function() { alert("hi"); } //]]> </script> </f:verbatim> 

You can see a detailed explanation when using CDATA here. You don’t need these if you are creating HTML5 pages.

Happy coding!

+9
source

Source: https://habr.com/ru/post/1311856/


All Articles