1

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.

3
  • 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'? Commented Oct 13, 2014 at 1:08
  • 1
    possible duplicate of JavaScript adding a string to a number Commented Oct 13, 2014 at 1: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. Commented Oct 27, 2014 at 0:05

2 Answers 2

5
$('.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%

Sign up to request clarification or add additional context in comments.

1 Comment

Please wrap .sameDiv in string delimiters…
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.

5 Comments

Please do not post solutions, but explain why as well!
@MichaelVoznesensky but you are right concerning explaining.
Per Bergi's comment in the other answer: Please wrap .sameDiv in string delimiters…
@ProllyGeek: FYI, the downvote tooltip text says "This answer is not useful". An answer can contain a correct solution but may not be useful.
@FelixKling thanks for the information , but useful is not a digital value , it may vary from person to another such question doesnt really require answering i would flag it as noob question if there was such option.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.