purple11111 purple11111 - 27 days ago 19
CSS Question

Get width in percentage from Resizable divs from jQuery UI on load and on resize

So I got these two divs next to each other. Both of the divs can already be resized by using the jQuery UI.

On resizing the divs I grab the width make it into a percentage and output it to the corresponding inputs but something strange happens.

The HTML:

<div id="parent">
<div id="div1"> My Data1
<input type="text" class="div1">
</div>
<div id="div2"> My Data2
<input type="text" class="div2">
</div>
</div>


The Javascript:

$("#div1").resizable();
$('#div1').resize(function(){
$('#div2').width($("#parent").width()-$("#div1").width());
});
$(window).resize(function(){

var div1width = $(".div1").width() / $('.div1').parent().width() * 100;
// Paste percentage into the inputs
$('.div1').val(div1width);

var div2width = $(".div2").width() / $('.div2').parent().width() * 100;
// Paste percentage into the inputs
$('.div2').val(div2width);
});


The CSS:

#parent{
position:absolute;
height:100%;
margin:0;
padding:0;
width:100%;
}
#div1{
position:relative;
float:left;
height:100%;
width:50%;
background-color:#A2A;
}
#div2{
position:relative;
float:left;
height:100%;
width:50%;
background-color:#BBB;
}
.ui-resizable-e {
cursor: e-resize;
width: 7px;
right: -5px;
top: 0;
height: 100%;
background: black;
}


The fiddle: https://jsfiddle.net/uvcxfmfy/1/

What happens is that when I make for instance div1 smaller the width percentage goes up even all the way over 800%. When I make it wider the width percentage stops at 20%. So something is wrong but I cant find it where.

What I am trying to achieve.



On page load both divs should have 50% width. When I make div1 smaller it should go all the way to 0% when I make it bigger it should go to 100%.

This means that if div1 is set at 25% that div2 will have 75%
When div1 is set at 58% then div2 is 42%.

Thanks everyone for helping.

Answer

I hope you find it helpful. You should use this math to get percent:

Math.round(( docWidth - elemWidth ) / docWidth * 100)

Im just order your code and change the calc line, look at this example:

$("#div1").resizable();

$('#div1').resize(function(){
   $('#div2').width($("#parent").width()-$("#div1").width()); 
});

$(window).resize(function(){
    elementResize()
});

$(document).ready(function(){
    elementResize()
});

function elementResize(){
   $('#div2').width($("#parent").width()-$("#div1").width()); 
   $('#div1').height($("#parent").height()); 

   var parentwidth = $("#parent").width(),
       div1width = $("#div1").width(),
       div2width = $("#div2").width(),
       div1percentage = Math.round((div1width / parentwidth) * 100),
       div2percentage = Math.round((div2width / parentwidth) * 100);

   $('.div1').val(div1percentage);
   $('.div2').val(div2percentage);
}

Fiddle demo

Comments