summing outerHeight with padding gives wrong result

417 Views Asked by At

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.

3

There are 3 best solutions below

1
Allan Empalmado On BEST 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>

0
Sunil Kumar On

I used to get your result by following code:

HTML Code:

<span id="resultHeight"></span>
<header></header>
<div class="container">

</div>

CSS Code:

header{height:474px;}
.container{height: 150px;}

JQuery Code:

var headerHeight = parseInt($('header').outerHeight());
    console.log(headerHeight);
    var containerPT = parseInt($(".container").outerHeight());
    console.log(containerPT);
    var totalSpace = (headerHeight + containerPT)+"px";
    $("#resultHeight").html(totalSpace);

Please refer below link :

Click here

Hope it helps you :)

0
AudioBubble On

You won't get the right result because you are adding 2 strings instead of 2 numbers. What you should do is convert them into numbers to get the right result. To do this use the parseInt() function.

var totalSpace = (parseInt(headerHeight) + parseInt(containerPT));
console.log(totalSpace + "px");

I hope this gives you the desired result.