1

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.

valerio0999
  • 11,458
  • 7
  • 28
  • 56

3 Answers3

1

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.

0

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>
Allan Empalmado
  • 943
  • 1
  • 6
  • 12
  • You provided the code and I just made corrections to it. You appended "px" to the variable output that's why it won't add the numerical value instead it will append since the variable will be considered a string. Can you check your console logs for errors? It should be working, you may have a typo, try copy pasting the code ;-) – Allan Empalmado Jul 03 '16 at 19:04
0

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 :)

Sunil Kumar
  • 3,142
  • 1
  • 19
  • 33