Search This Blog

Thursday, June 20, 2013

Height problem when rendering an ExtJs 4 application in a custom div

This post is verified with Ext Js version 4.

ExtJs applications can be run in the whole browser window or in a small part of a larger application, for example in a div. You may want to render an ExtJs application in a div if you have a common HTML structure with navigation capabilities outside the ExtJs application. To render an ExtJs application to a div do the following:

  • create an HTML which contains the div where the application is rendered
  • Create an app.js file which is the actual ExtJs application. 
Below is an example of an index.html with a div named appContent where the ExtJs application is rendered to:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>Sample app</title>
    <script type="text/javascript" src="extjs/ext-debug.js"></script>
    <script type="text/javascript" src="extjs/ext-theme-neptune.js"></script>
    <script type="text/javascript" src="app.js"></script>
</head>
<body>
<div id="appContent" class="app-content">

</div>
</body>
</html>

And here is an example of app.js which renders the application to a div:

Ext.application({
    name: "SampleApp",
    launch: function () {
        Ext.create("Ext.panel.Panel", {
            renderTo: Ext.getElementById("appContent"),
            autoCreateViewPort: false,
            layout: {
                type: "hbox",
                align: "stretch"
            },
            id: "appContainer",
            listeners: {
                beforerender: function () {
                    Ext.getCmp("appContainer").setHeight(Ext.get("appContent").getHeight());
                    Ext.getCmp("appContainer").doLayout();

                    Ext.EventManager.onWindowResize(function () {
                        Ext.getCmp("appContainer").setHeight(Ext.get("appContent").getHeight());
                        Ext.getCmp("appContainer").doLayout();
                    });
                }
            },
            items: [
                {
                    xtype: "label",
                    text: "Sample App",
                    flex: 1
                }
            ]
        });
    }
});

Please notice the listeners section. What I noticed was that with some layouts (for example the hbox, vbox and borderlayout) the application did not occupy the whole size of the div. When I rendered the same application using a viewport the application size was a large as the browser window.

The beforerender listener fixes this issue. It basically sets the height of the application container to the height of the div and calls doLayout to update the view. This same logic is also added to the onWindowResize event to adjust the size of the application when the browser window is resized. This fixed the problem for me.