1

I want to be able to access a controller property with Javascript to do some styling (based on the value of this property) so that it appears visually to be executed immediately on page load. However, this styling will depend on components of an apex:repeat, so I need to call the JS after everything has been rendered, but before the user takes any action.

Currently, I can access the properties dynamically with JS (once the page is loaded and settled) no problem by using a variable held in an outputPanel that I rerender when someone changes a dropdown (to capture the updated variable from the controller and reflect that value on the page):

<apex:outputPanel id="rerenderTypeToSet">
    <script type="text/javascript">
        var styleType = {!someControllerValue};
    </script>
</apex:outputPanel>

I found the following snippet on the developer forums to execute JS on page load:

<script> 
var previousOnload = window.onload; 
window.onload = function() { 
   if (previousOnload) { previousOnload(); } 
   alert('loading...'); 
} 
</script>

Which works great when this simple alert(string) is used. However, if I substitute in alert(styleType);, the alert doesn't fire, because I haven't rerendered the outputPanel holding the JS variable.

What is the best method to call Javascript that can access controller properties so that it appears to be visually happening on page load? Perhaps some way to immediately rerender that outputPanel on pageload and then immediately after call the JS? Any ideas are welcome.

2

You don't need two script statements. I would make sure to escape your controller properties though. I still usually use jQuery for event listeners but the gist is below:

<script>
    (function (w, $) {
        "use strict";
        var styleType = {!JSENCODE(someControllerValue)};
        $(function () { // window.onload
            alert(styleType);
        });
    })(window, jQuery.noConflict());
</script>

I haven't had any issues with the controller properties not being instantiated when I call snippets like the above.

  • 1
    In other words, when the page is "ready" (which occurs after parsing but before the "load" event occurs). – sfdcfox Apr 22 '15 at 5:25
  • There was an embarrassing error in my controller - I ended up getting vanilla JS to work, but I took a look into jquery and it looks like something I definitely need to pick up (been saying that for two years now!). Thanks guys! – Brian Mansfield Apr 22 '15 at 13:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.