Get width as a percentage of resized divs from jQuery user interface when loading and resizing

So, I got these two divs next to each other. Both of the divs can already be modified using the jQuery user interface.

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

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>

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);
});

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;
}

Scenario: https://jsfiddle.net/uvcxfmfy/1/

What happens is that when I make, for example, div1 smaller, the percentage of width increases even by 800%. When I do it wider, the percentage percentage stops at 20%. So something is wrong, but I can’t find it where.

What I'm trying to achieve.

div 50%. div1 , 0%, , 100%.

, div1 25%, div2 75% div1 58%, div2 42%.

.

+4
1

, . :

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

, :

$("#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);
}

+1

Source: https://habr.com/ru/post/1660205/


All Articles