weyhei
weyhei

Reputation: 479

Javascript/Jquery - Addition and Subtraction error

I have the following script to get the height of the browser, then the height of header and footer then subtract from the height of the browser:

var a = $(window).height();
alert (a);
var b = $('#header').css('height').replace(/[^-\d\.]/g, '');
alert (b);
var c = $('#header').css('height').replace(/[^-\d\.]/g, '');
alert (c);
var d = (a-(b+c));
alert (d);
$('#block').height(d);

SO it alerts,
1.)699
2.)100
3.)50
then the wrong part:
4.)-9351

What part is wrong here?

Upvotes: 0

Views: 355

Answers (4)

soonji
soonji

Reputation: 79

try this...just replace the fixed numbers

var a = parseInt('600');
var b = parseInt('100');
var c = parseInt('50');
var d = (a-(b+c));

Upvotes: 0

gabitzish
gabitzish

Reputation: 9691

Use parseInt :

var a = parseInt($(window).height());
alert (a);
var b = parseInt($('#header').css('height').replace(/[^-\d\.]/g, ''));
alert (b);
var c = parseInt($('#header').css('height').replace(/[^-\d\.]/g, ''));
alert (c);
var d = (a-(b+c));
alert (d);
$('#block').height(d);

Upvotes: 2

Anoop
Anoop

Reputation: 23208

You can use jquery height( returns integer) method.in your code b and c are string. jsfiddle

 var a = $(window).height();
    alert (a);
    var b = $('#header').height();
    alert (b);
    var c = $('#header').height();
    alert (c);
    var d = (a-(b+c));
    alert (d);
    $('#block').height(d);

Upvotes: 1

Tim Lamballais
Tim Lamballais

Reputation: 1054

The vars b and c contain Strings, when you use the + operator on Strings in Javascript they are concatenated.

i.e. the expression "100" + "50" evaluates to "10050".

I suggest getting the height of the elements with the jQuery .height() method

Upvotes: 4

Related Questions