Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to embed and call a javascript script in a RichFaces/JSF page

I've been looking around for a method to embed and call javascript functions in JSF pages. I'm also using RichFaces.

To define the function, it appears I can do this in a cross-browser supported fashion:

        <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 it returns is embedded in an h:outputPanel. The plan is to have a js clock embedded in the page which is served to the client. Note I'm not using the body tag, I'm using facelets ui:composition, f:view (core) and RF RI rich:page.

Thanks

like image 693
volvox Avatar asked Feb 26 '23 21:02

volvox


1 Answers

Regardless of what sorts of server-side tags you're using, by the time your page gets to the browser that's all gone and it's just HTML. (At least, it had better be, or things won't work anyway.) What you need to do is arrange for your code to be called by a "load" event handler. There are various ways to do this, but the simplest would be this:

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

Now as to initializing another part of the page, once again what matters is what ends up in the HTML. You'll want to arrange for there to be some sort of HTML container (a <div> or something, depending on your page design) and you'll want it to have a unique "id" attribute. Your Javascript can then use the "id" to find the element and set its contents:

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

You'd probably do that stuff inside the "load" function.

Also, if you're using Facelets instead of JSP, which is a XML based view technlogy, you will need to add the XML CDATA section delimiters if your JavaScript contains comments // or literals such as <, >, &&, etc. Here's the example with the 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 thorough explanation of when to use CDATA here. You do not need those if you're creating HTML5 pages.

Happy coding!

like image 171
Pointy Avatar answered Mar 08 '23 23:03

Pointy