Search code examples
jquery-uijquery-ui-resizable

How to resize floated elements so that their total width is always 100% of a parent container?


I have three divs inside a container floating left and each div taking up 33.3% (1/3) of the width of the container. I want to be able to resize any of them which will resize the closest sibling inversely so that the width of all three divs will always be 100% of the width of the container.

jquery resizable call:

var containerWidth = $("#container").width();
$(".box").resizable({
handles: "e",
containment: "#container",
resize: function(e,ui){
    var totalSize = ui.size.width;
    ui.element.siblings(".box").each(function(){
    totalSize = totalSize + $(this).width();
  });
  var direction = totalSize > containerWidth ? -1 : 1;
  var nextBox = ui.element.next(".box");
  var nextBoxWidth = nextBox.width();
  nextBox.width(nextBoxWidth + direction);
}
});

Please use this jsfiddle to see the issues I am experiencing:

jsfiddle

In the example, I am getting the width of the container and comparing it to the total size of the boxes during the resize event. This should tell me whether or not the current box is being sized down or sized up and thus the nearest sibling should be sized up or sized down. This clearly isn't working.

Does anyone know of a way to accomplish what I am trying to do? Perhaps there is a way to use the alsoResize option in the plugin?


Solution

  • You are just increasing the nextBox width by +/-1px. I think you should replace that line with the following:

    var extraWidth = containerWidth - totalSize;
    nextBox.width(nextBoxWidth + extraWidth);
    

    First line tells you how wide is the free space after resizing; you then incremenent the nextBox width of the same amount (see here)