Danferth
Danferth

Reputation: 1879

Add in integer to returned value with jQuery

I have a page with a div id="videoFrame" that holds the video tag. The videos have variable heights so I have a function to grab the height value and plug it into the css of the div id="videoFrame" like so:

var videoHeight = $('video').attr('height');
$('#videoFrame').css('height',videoHeight+'px');

This works great. But here's the part driving me crazy. I have a p tag with disclaimers at the bottom of the div id="videoFrame". So I would like to add an additional 26px to the returned height. I tried:

var videoHeight = $('video').attr('height');
var frameHeight = videoHeight + 26;
$('#videoFrame').css('height',frameHeight+'px');

But as you would expect it is adding 26 to the end of the returned value. i.e. if returned value is 337 output for var frameHeight is 33726.

I can not for the life of me figure out how to do this.

Thanks in advance for any help

Upvotes: 2

Views: 2891

Answers (7)

vgardner
vgardner

Reputation: 517

var videoHeight = parseInt($('video').attr('height'));
var frameHeight = videoHeight + 26;

Upvotes: 0

dnuttle
dnuttle

Reputation: 3830

var frameHeight = parseInt(videoHeight,10) + 26;

Upvotes: 0

Moe Sweet
Moe Sweet

Reputation: 3721

ParseInt before you add.

var frameHeight = parseInt(videoHeight) + 26;

Upvotes: 1

jfriend00
jfriend00

Reputation: 707148

$('video').attr('height') returns a string. Adding a number to a string converts the number to a string and adds the two strings which is not what you want. You want to add two numbers. So, you must convert this string to a number so you can then add two numbers:

var videoHeight = parseInt($('video').attr('height'), 10);
var frameHeight = videoHeight + 26;

There are a several ways to convert a string to a number. Here are a few of the more obvious ones.

parseInt(str, radix)
parseFloat(str)
Number(str)

When using parseInt, always specify the radix, otherwise, it will guess based on the content of the string (which you almost never want).

Upvotes: 4

mnsr
mnsr

Reputation: 12437

You have to use parseInt

var videoHeight = parseInt($('video').attr('height'));

Upvotes: 0

Robert Van Sant
Robert Van Sant

Reputation: 1507

you should wrap parseInt() around the videoHeight variable. try that, i hope this helps.

Upvotes: 0

CodeMonkeyG
CodeMonkeyG

Reputation: 185

Try this.

var frameHeight = Number(videoHeight) + 26;

Upvotes: 0

Related Questions