Search code examples
jqueryjquery-uijquery-ui-resizable

jquery ui: resize also triggers a resize on `window`


I've found this nice splitter here on stackoverflow (jsfiddle). Because all the sizes are set in pixels it is not very response. So I changed them to percentages (jsfiddle). Now, if you move the splitter, and next try to change the window size it still breaks.

In order to fix this I tried adding a listener on the window object

$(window).on('resize', function () {
    /* reset width of both elements to percentages */
});

jsfiddle

This code should only be triggered when the window size changes. Unfortunately, it is also called when jquery-ui triggers the 'resize' event. Any suggestions how to stop the propagation of that event when triggered by jquery-ui ?

If there is already a responsive splitter, please let me know!


Solution

  • In order to trigger the code only when window resizes, you can try using e.target.

    Demo: http://jsfiddle.net/lotusgodkk/8qzTJ/740/

    $(function () {
    var el1, el2;
    
    $(".resizable1").resizable({
        handles: 'e',
        minWidth: '50',
        resize: function (event) {
            var remainingSpace = $(this).parent().width() - $(this).outerWidth(),
                divTwo = $(this).next(),
                divTwoWidth = remainingSpace - (divTwo.outerWidth() - divTwo.width());
            divTwo.width(divTwoWidth);
            el1 = $(this);
            el2 = divTwo;
    
            event.stopPropagation();
            //event.preventDefault();
            return false;
        }
    });
    
    $(window).on('resize', function (e) {
        console.log($(e.target).hasClass('ui-resizable'));
        if (!$(e.target).hasClass('ui-resizable')) {//Check whether the target has class "ui-resizable".
            console.log('window');
            if (el1 && el2) {
                el1.width('50%');
                el2.width('50%');
            }
        }
     });
    });
    

    Here before executing the resize function, I am checking whether the target has class "ui-resizable". jQuery adds a class "ui-resizable" on the binding elements. Hope this helps.