Search code examples
jsfprimefacesstickywindow-resize

<p:sticky> doesn't resize on window resize


I'm using <p:sticky> with a menu. My problem is that it does not resize when the window is resized.

How can I make the <p:sticky> to resize as well when the window is resized?


Solution

  • OK, so as I said in my comment above, the problem is that Primefaces only calculates the width of the target once, on initialization. After that it's a fixed number that doesn't change.

    So what we have to do is to re-initialize the component. I've tried it out on the Primefaces Showcase page.

    The following client-side Javascript almost does the trick:

    foo = PF('widget_j_idt93');
    foo.init(foo.cfg);
    

    (Here "widget_j_idt93" is the widgetVar of the Primefaces component. Substitute your own as appropriate.)

    What is missing is that Primefaces (quite correctly) thinks that the widget already is initialized. In order to un-initialize the widget, we can first remove all the element styles:

    $("#tb").attr("style","")
    

    (Where "#tb" is the selector of the target, i.e. your menu.)

    So if you make a function that first removes the styles and then resets the widget, it should work.

    Edit: After looking at the client-side code of the Sticky component I figured it out. You have to restore before you blank and initialize, and then you have to explicitly run the sticky-or-not call. So this should be the solution:

    fixSticky = function() {
        var bla=PF('widget_j_idt93');
        bla.restore();
        bla.target.attr("style","");
        bla.init(bla.cfg);
        if($(window).scrollTop() > bla.initialState.top) {bla.fix();} else {bla.restore();}
    }
    

    Simply run this function (modified to your own widgetVar, or maybe with a parameter) whenever the page is resized.