Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to avoid the nan error in javascript?

I need the height of several containers to be subtracted from a number (for example 1000) at the same time this number must be a css value (in this case 1000px).
But when I add the height of the containers and subtract it from the number 1000 I get the NaN error.
I need an answer without the use of jquery.
This is the code:

let carouselHeight = document.getElementById("carouselExampleAutoplaying").offsetHeight;
let cardHeaderHeight = document.getElementById("cardHeaderDiv").offsetHeight;
let navbarHeight = document.getElementById("navDiv").offsetHeight;
let bannerHeight = document.getElementById("topBannerDiv").offsetHeight;
let CardBody = document.getElementById('CardBody');
CardBody.setAttribute('style', 'height: ' + 1000 - bannerHeight - navbarHeight - cardHeaderHeight - carouselHeight + 'px');

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is concatenating strings and trying to perform math on strings:

'height: ' + 1000 - bannerHeight - navbarHeight - cardHeaderHeight - carouselHeight + 'px'

Specifically, it’s first doing 'height: ' + 1000 which results in the string value 'height1000', then it’s trying to do: 'height1000' - bannerHeight, the result of which is not a number because you can’t subtract from a string.

For example:

const bannerHeight = 1;
const navbarHeight = 2;
const cardHeaderHeight = 3;
const carouselHeight = 4;
const result = 'height: ' + 1000 - bannerHeight - navbarHeight - cardHeaderHeight - carouselHeight + 'px';
console.log(result);

But you intended this part to be math:

1000 - bannerHeight - navbarHeight - cardHeaderHeight - carouselHeight

Perform the math first, then use the result in your string. Which you could do as a separate operation, or by simply wrapping the expression in parentheses to control the order of operations:

'height: ' + (1000 - bannerHeight - navbarHeight - cardHeaderHeight - carouselHeight) + 'px'

For example:

const bannerHeight = 1;
const navbarHeight = 2;
const cardHeaderHeight = 3;
const carouselHeight = 4;
const result = 'height: ' + (1000 - bannerHeight - navbarHeight - cardHeaderHeight - carouselHeight) + 'px';
console.log(result);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading