views:

331

answers:

1

Hello

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

+2  A: 

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.

Pointy
@pointy - I realised about the server tags but wanted to be unambiguous regarding then calling this function within the jsf code. I'd not realised I could use window.onload within the js itself. Thanks
Mark Lewis
OK best of luck! Thanks for accepting the answer.
Pointy
Oh, also, a warning (probably obvious) - as soon as you need *two* things to be called at "load" time (esp. when they're in unrelated server-side code units), you're going to want a fancier setup for managing those handler functions. That's where the various Javascript frameworks start to be a big help.
Pointy