2

This works:

$('.sameDiv').css('width', '25%');

But this doesn't:

var squaresize = 25;
$('.sameDiv').css('width', 'squaresize%');

Also, I've tried it with the percent symbol as part of the variable and that doesn't help.

Arnold Daniels
  • 16,516
  • 4
  • 53
  • 82
Laura Gyre
  • 141
  • 8
  • 2
    What made you think JavaScript would substitute variable names in strings? Given `var foo = 42;` did you think that `var bar = 'foobar';` would be turned into `'42bar'`? – Felix Kling Oct 13 '14 at 01:08
  • 1
    possible duplicate of [JavaScript adding a string to a number](http://stackoverflow.com/questions/16522648/javascript-adding-a-string-to-a-number) – ProllyGeek Oct 13 '14 at 01:16
  • For things that are JQuery + Javascript, it's often better to use JQuery in the title instead of Javascript, to get the right folks to answer. – Dean J Oct 27 '14 at 00:05

2 Answers2

6
$('.sameDiv').css('width', 'squaresize%');

Should become

$('.sameDiv').css('width', squaresize + '%');

I did not test it, but if you just put 'squaresize%' it will not try to reference it... rather, just read it directly as a literal string evaluating to "squaresize%" instead of 25%

Michael Voznesensky
  • 1,612
  • 12
  • 15
1

Your code should be like:

var squaresize = 25;

$(".sameDiv").css('width', squaresize+'%');

Your variable name is "squaresize". Knowing that when adding a string to an integer will produce a string as well, there is no need to convert your integer to a string. Just add the "%" to your variable value.

Using a single quote, you are setting css to value 'square%' as a static value.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ProllyGeek
  • 15,517
  • 9
  • 53
  • 72