Reputation: 541
I'm trying to sum the innerWidth
and constant numbers
in JS, but the browser keeps just attaching those numbers, not calculating.
The weird thing is giving minus values are working fine. The browser doesn't calculate only when I try to sum the numbers to innerWidth
.
Are there any ways to solve this issue?
Slider.prototype.sizeReseting = function(event) {
this.frame.style.height = (window.innerWidth - '300') + 'px';
this.frame.style.width = (window.innerWidth - '300') + 'px';
this.film.style.height = (window.innerWidth - '400') + 'px';
this.film.style.width = (window.innerWidth + '100') + 'px';
}
Upvotes: 2
Views: 401
Reputation: 11806
Because you are concatenating strings.
In JavaScript, strings are defined between quotes or double quotes. Hence var thing = 100;
is a number but var thing = '100';
is a string.
Strings are just a bunch of characters, with no numeral value (Not actually true, but for you to understand this easily). Having a string var thing = '100';
has the same number value as having the string var thing = 'asd';
, which is none.
Concatenating two strings gives the concatenation as a result, hence "asd" + "zxc"
result in "asdzxc"
, the same way you concatenate two strings like this: "100" + "100"
results in "100100"
.
For your code to work, just remove the string delimitation and sum actual numbers, like this:
this.film.style.width = (window.innerWidth + 100) + 'px';
Note how I removed the single quotes around 100
for it to be an actual number.
Upvotes: 6
Reputation: 2416
This 2 lines have very different results:
this.film.style.height = (window.innerWidth - '400') + 'px';
this.film.style.width = (window.innerWidth + '100') + 'px';
In the first one, the sign -
converts your sting 400
to a number. Therefore, you're substracting 400 to the value of window.innerWidth (and then adding the string 'px')
In the second one, the sign +
is acting as a concatenation operator. Therefore, you're concatenating the result of window.innerWidth
+ the string '100'
+ the string 'px'
.
Just remove the single quotes from your code:
this.film.style.width = (window.innerWidth + 100) + 'px';
Upvotes: 2