[SalesForce] Passing a javascript variable value to component attribute value

I have a VF custom component with attribute called chartHeight.
I need to assign chartHeight a value from the VF page the component resides in, and this value should be screen.availHeight retrived using from JS.
How can I pass screen.availHeight as the atrribute's value?

<c:PartitionChart JsonData="{!JsnString}" chartHeight=**<need to pass this>** chartWidth="800"/>


<apex:attribute name="chartHeight" description="Chart Height" type="integer" required="true" />

Best Answer

On principle, it's a shame to hand the browser dimensions to a server-side component.

But you can definitely do this as a multi stage process if you really have to:

  1. render your empty page, first determining the viewport size using JavaScript,
  2. populate some hidden form field with that height and invoke an actionFunction,
  3. use the actionFunction rerender to draw your chart component using the newly persisted height.

image-size

The general idea is to grab the window size of the browser, transmit it to the server in a form submission and then draw the chart using a {!Height} controller property, like this:

<apex:page controller="ChartHeightController">
    <apex:form>

        <apex:inputHidden id="Field" value="{!Height}" />
        <apex:actionFunction name="doResize" rerender="chart" />
        <c:PartitionChart id="chart" JsonData="{!JsnString}" chartHeight="{!Height}" chartWidth="800" />

        <script>
            var windowOnload = window.onload;
            window.onload = function() {
                if (windowOnload) windowOnload(); //be nice, don't trash existing onload
                document.getElementById('{!$Component.Field}').value = window.innerHeight;
                doResize();
            }
        </script>

    </apex:form>
</apex:page>

The controller just provides a dumb target for the height to hang around in the viewstate.

public class ChartHeightController {

    public Integer Height {get; set;}

}
Related Topic