Resize jqGrid when browser is resized?
Asked Answered
N

12

81

Is there any way to resize a jqGrid when the browser window is resized? I have tried the method described here but that technique does not work in IE7.

Newspaperman answered 17/5, 2009 at 18:58 Comment(0)
N
53

As a follow-up:

The previous code shown in this post was eventually abandoned because it was unreliable. I am now using the following API function to resize the grid, as recommended by the jqGrid documentation:

jQuery("#targetGrid").setGridWidth(width);

To do the actual resizing, a function implementing the following logic is bound to the window's resize event:

  • Calculate the width of the grid using its parent's clientWidth and (if that is not available) its offsetWidth attribute.

  • Perform a sanity check to make sure width has changed more than x pixels (to work around some application-specific problems)

  • Finally, use setGridWidth() to change the grid's width

Here is example code to handle resizing:

jQuery(window).bind('resize', function() {

    // Get width of parent container
    var width = jQuery(targetContainer).attr('clientWidth');
    if (width == null || width < 1){
        // For IE, revert to offsetWidth if necessary
        width = jQuery(targetContainer).attr('offsetWidth');
    }
    width = width - 2; // Fudge factor to prevent horizontal scrollbars
    if (width > 0 &&
        // Only resize if new width exceeds a minimal threshold
        // Fixes IE issue with in-place resizing when mousing-over frame bars
        Math.abs(width - jQuery(targetGrid).width()) > 5)
    {
        jQuery(targetGrid).setGridWidth(width);
    }

}).trigger('resize');

And example markup:

<div id="grid_container">
    <table id="grid"></table>
    <div id="grid_pgr"></div>
</div>
Newspaperman answered 15/10, 2009 at 21:12 Comment(3)
If you need to support IE you might want to throttle the frequency of resizing via timers.Kelantan
Care to elaborate? I had problems on IE when the resize event was called without the grid changing width, which led to strange behavior on the grid itself. That is why the code takes into account a threshold in step 2.Newspaperman
What if I want to change of the css for the add/edit form of jqgrid ?Knobkerrie
S
69

Been using this in production for some time now without any complaints (May take some tweaking to look right on your site.. for instance, subtracting the width of a sidebar, etc)

$(window).bind('resize', function() {
    $("#jqgrid").setGridWidth($(window).width());
}).trigger('resize');
Superposition answered 27/10, 2009 at 19:20 Comment(2)
Also very useful in this situation: The second parameter to setGridWidth is 'shrink'. #7745509Inoculation
Stephen, did you see jmav's solution? This seems like the best one but I wanted to see how you contrasted it with this approachBurdett
N
53

As a follow-up:

The previous code shown in this post was eventually abandoned because it was unreliable. I am now using the following API function to resize the grid, as recommended by the jqGrid documentation:

jQuery("#targetGrid").setGridWidth(width);

To do the actual resizing, a function implementing the following logic is bound to the window's resize event:

  • Calculate the width of the grid using its parent's clientWidth and (if that is not available) its offsetWidth attribute.

  • Perform a sanity check to make sure width has changed more than x pixels (to work around some application-specific problems)

  • Finally, use setGridWidth() to change the grid's width

Here is example code to handle resizing:

jQuery(window).bind('resize', function() {

    // Get width of parent container
    var width = jQuery(targetContainer).attr('clientWidth');
    if (width == null || width < 1){
        // For IE, revert to offsetWidth if necessary
        width = jQuery(targetContainer).attr('offsetWidth');
    }
    width = width - 2; // Fudge factor to prevent horizontal scrollbars
    if (width > 0 &&
        // Only resize if new width exceeds a minimal threshold
        // Fixes IE issue with in-place resizing when mousing-over frame bars
        Math.abs(width - jQuery(targetGrid).width()) > 5)
    {
        jQuery(targetGrid).setGridWidth(width);
    }

}).trigger('resize');

And example markup:

<div id="grid_container">
    <table id="grid"></table>
    <div id="grid_pgr"></div>
</div>
Newspaperman answered 15/10, 2009 at 21:12 Comment(3)
If you need to support IE you might want to throttle the frequency of resizing via timers.Kelantan
Care to elaborate? I had problems on IE when the resize event was called without the grid changing width, which led to strange behavior on the grid itself. That is why the code takes into account a threshold in step 2.Newspaperman
What if I want to change of the css for the add/edit form of jqgrid ?Knobkerrie
P
36

Auto resize:

For jQgrid 3.5+

        if (grid = $('.ui-jqgrid-btable:visible')) {
            grid.each(function(index) {
                gridId = $(this).attr('id');
                gridParentWidth = $('#gbox_' + gridId).parent().width();
                $('#' + gridId).setGridWidth(gridParentWidth);
            });
        }

For jQgrid 3.4.x:

       if (typeof $('table.scroll').setGridWidth == 'function') {
            $('table.scroll').setGridWidth(100, true); //reset when grid is wider than container (div)
            if (gridObj) {

            } else {
                $('#contentBox_content .grid_bdiv:reallyvisible').each(function(index) {
                    grid = $(this).children('table.scroll');
                    gridParentWidth = $(this).parent().width() – origami.grid.gridFromRight;
                    grid.setGridWidth(gridParentWidth, true);
                });
            }
        }
Probably answered 22/10, 2009 at 21:54 Comment(3)
Well, I can confirm that the 3.5+ version above works great with jqGrid 4.4.1 on IE9, but with FireFox 16 an 17, the table keeps growing slightly wider every time I adjust the browser width.Doolie
Maybe you have problems with borders, defined in css - I did.Probably
You will probably want to pass true as the second param in your setGridWidth() call in recent versions of jqGrid. If you don't the columns in your table aren't resized when the table resizes. ie $(this).setGridWidth(gridParentWidth, true);Buckra
A
8

this seems to be working nicely for me

$(window).bind('resize', function() {
    jQuery("#grid").setGridWidth($('#parentDiv').width()-30, true);
}).trigger('resize');
Achaean answered 29/9, 2010 at 22:7 Comment(3)
Thanks for the solution, but it didn't working properly, like it changes whole div, but don't apply for header. :(Polypus
Why there is -30 in your example?Chromoprotein
i'm not sure. It was 5 years ago :(Achaean
B
7

I'm using 960.gs for layout so my solution is as follows:

    $(window).bind(
        'resize',
        function() {
                    //  Grid ids we are using
            $("#demogr, #allergygr, #problemsgr, #diagnosesgr, #medicalhisgr").setGridWidth(
                    $(".grid_5").width());
            $("#clinteamgr, #procedgr").setGridWidth(
                    $(".grid_10").width());
        }).trigger('resize');
// Here we set a global options

jQuery.extend(jQuery.jgrid.defaults, {
    // altRows:true,
    autowidth : true,
    beforeSelectRow : function(rowid, e) { // disable row highlighting onclick
        return false;
    },
    datatype : "jsonstring",
    datastr : grdata,  //  JSON object generated by another function
    gridview : false,
    height : '100%',
    hoverrows : false,
    loadonce : true,
    sortable : false,
    jsonReader : {
        repeatitems : false
    }
});

// Demographics Grid

$("#demogr").jqGrid( {
    caption : "Demographics",
    colNames : [ 'Info', 'Data' ],
    colModel : [ {
        name : 'Info',
        width : "30%",
        sortable : false,
        jsonmap : 'ITEM'
    }, {
        name : 'Description',
        width : "70%",
        sortable : false,
        jsonmap : 'DESCRIPTION'
    } ],
    jsonReader : {
        root : "DEMOGRAPHICS",
        id : "DEMOID"
    }
});

// Other grids defined below...

Bazemore answered 11/11, 2010 at 21:23 Comment(0)
R
5

If you:

  • have shrinkToFit: false (mean fixed width columns)
  • have autowidth: true
  • don't care about fluid height
  • have horizontal scrollbar

You can make grid with fluid width with following styles:

.ui-jqgrid {
  max-width: 100% !important;
  width: auto !important;
}

.ui-jqgrid-view,
.ui-jqgrid-hdiv,
.ui-jqgrid-bdiv {
   width: auto !important;
}

Here is a demo

Reviere answered 9/2, 2015 at 12:58 Comment(0)
T
4

Borrowing from the code at your link you could try something like this:

$(window).bind('resize', function() { 
    // resize the datagrid to fit the page properly:
    $('div.subject').children('div').each(function() {
        $(this).width('auto');
        $(this).find('table').width('100%');
    });
});

This way you're binding directly to the window.onresize event, which actually looks like what you want from your question.

If your grid is set to 100% width though it should automatically expand when its container expands, unless there are some intricacies to the plugin you're using that I don't know about.

Thadeus answered 17/5, 2009 at 19:18 Comment(2)
Thanks for the tip! Turns out that I was calling the resize code from the GridComplete event - for whatever reason this does not work in IE. Anyway, I extracted out the resize code into a separate function and call it both in the resize function and after the grid is created. Thanks again!Newspaperman
This doesn't work when resizing a window in IE 8 I believe. It does when you refresh the page though.Cubital
C
3

The main answer worked for me but made the app extremely unresponsive in IE, so I used a timer as suggested. Code looks something like this ($(#contentColumn) is the div that the JQGrid sits in):

  function resizeGrids() {
    var reportObjectsGrid = $("#ReportObjectsGrid");
    reportObjectsGrid.setGridWidth($("#contentColumn").width());
};

var resizeTimer;

$(window).bind('resize', function () {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(resizeGrids, 60);
});
Chiliarch answered 5/4, 2011 at 14:6 Comment(6)
It seems like it would be tricky to make the timer work properly. Can you please take a look at my updated answer and see if you still need the timer?Newspaperman
Just compared all 3 of them. Yours is definitely an improvement over Stephens solution but the resizing of the window is still quite jerky. With the timer the resizing is smooth until the event fires so it takes a bit of fiddling to get timing trigger duration right. The timer is a bit clumsy, but I think it gives the best results in the end.Chiliarch
edit: Stephens sln works fine on another page of mine...this page only started to struggle once I had added a bunch of other jQueryUI controls to it.Chiliarch
This is a very dumb question. But I am a complete NOOB at Jquery, so please very much forgiving, but where are we placing all these functions? Inside the Jquery(document).ready(function() {} or are we sticking it out? Just wondering, also, where is $(window) and width coming from?Cubital
@DmainEvent, I put the $(window).bind in $(Document).ready, and the reszieTimer var and resizeGrids function outside the $(Document).ready. $(window) is the window element that is built into jquery and .width() is a jquery function that calculates the width of an elementChiliarch
What if I want to change of the css for the add/edit form of jqgrid ?Knobkerrie
C
3

Hello Stack overflow enthusiasts. I enjoyed most of answers, and I even up-voted a couple, but none of them worked for me on IE 8 for some strange reason... I did however run into these links... This guy wrote a library that seems to work. Include it in your projects in adittion to jquery UI, throw in the name of your table and the div.

http://stevenharman.net/blog/archive/2009/08/21/creating-a-fluid-jquery-jqgrid.aspx

http://code.google.com/p/codeincubator/source/browse/#svn%2FSamples%2Fsteveharman%2FjQuery%2Fjquery.jqgrid.fluid%253Fstate%253Dclosed

Cubital answered 26/8, 2011 at 13:1 Comment(1)
I'm also getting some strange behaviour in IE8 with and without compatability view :/ My grid is resizing to half the size it should be...thanks for the linksChiliarch
P
1
autowidth: true

worked perfectly for me. learnt from here.

Particulate answered 4/12, 2010 at 11:13 Comment(2)
autowidth works fine when the grid is first loaded, but will not resize the grid when the browser is resized. How did you deal with that problem, or is that not a requirement for you?Newspaperman
@Justin Ethier: you're right. I wanted it to set when grid is first time loaded, not when browser is resized. Sorry I misread the question. I understand down vote.Particulate
J
1

This works..

var $targetGrid = $("#myGridId");
$(window).resize(function () {
    var jqGridWrapperId = "#gbox_" + $targetGrid.attr('id') //here be dragons, this is     generated by jqGrid.
    $targetGrid.setGridWidth($(jqGridWrapperId).parent().width()); //perhaps add padding calculation here?
});
Jiggerypokery answered 3/9, 2013 at 12:30 Comment(0)
A
0
<script>
$(document).ready(function(){    
$(window).on('resize', function() {
    jQuery("#grid").setGridWidth($('#fill').width(), false); 
    jQuery("#grid").setGridHeight($('#fill').height(),true); 
}).trigger('resize');      
});
</script>
Almond answered 9/5, 2013 at 7:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.