valerio0999 valerio0999 - 5 months ago 18
Javascript Question

summing outerHeight with padding gives wrong result

i want to sum the outerheight() value of a div with the padding-top value of another div. here's my function

var headerHeight = $('header').outerHeight() + "px";
console.log(headerHeight);
var containerPT = $(".container").css('padding-top');
console.log(containerPT);
var totalSpace = (headerHeight + containerPT);
console.log(totalSpace);


and the result is:

//headerHeight
474px
//containerPT
150px
//totalSpace
474px150px


the result i need is of course 474 + 150 = 624px;
I usually sum stuff with ease, I'm not sure why this is happening and what I am doing wrong.
any help greatly appreciated.

Answer

I created a working demo, you still should parse the values. Somehow jQuery is still returning it as string and also added a replace method to remove px on retrieving css values like from the padding-top. check the updated code below

    var headerHeight = $('header').outerHeight();
    console.log(headerHeight + "px");
    var containerPT = $(".container").css('paddingTop').replace(/[^-\d\.]/g, '');

    console.log(containerPT + "px");
    var totalSpace = (parseInt(headerHeight) + parseInt(containerPT));
    console.log(totalSpace + "px");
header { height:200px; padding : 20px;}
.container { padding-top: 150px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>
  
 </header>
<div class="container">
  
 </div>