Reputation: 1702
I'm trying to set the width on an elemrnt to 100% minus a variable in pixels.
My subtractWidth
variable returns a dynamic value in pixels eg: 170
$('#chartTitle').each(function(i){
var elem = $(this);
var parent = $(elem).parent();
var next = $(parent).next();
var maxWidth = '100%';
var subtractWidth = next.width();
elem.width(maxWidth) - subtractWidth;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input id="chartTitle" />
</div>
<div> ... </div>
Am I mising something?
Any help or advice is appreciated - thank you in advance.
Upvotes: 0
Views: 776
Reputation: 7923
First apply the 100% width and then do the calculation based on the applied width.
Your problem is that in your line elem.width(maxWidth) - subtractWidth;
elem is setting the maxWidth which is 100% but not subtracting it after.
calculate = function(){
var total = '50%';
var subtractWidth = $('#div1').width();
$('#div2').width(total)
$('#div2').width($('#div2').width() - subtractWidth);
}
div{
background-color: red;
height: 20px;
display: block;
width: 0px;
}
#div1{
width: 70px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1"></div>
<hr>
<div id="div2"></div>
<hr>
<button onclick="calculate()">calculate</button>
Upvotes: 2