Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
How do I put a variable in a string in JavaScript?
Example:
$('#contactForm').animate({"marginLeft": "+=680px"}, "slow");
I would like to use in a variable instead of 680px, is there a way to do this?
680px
As with most languages that don't have sigals, you can't perform interpolation, you have to concatenate multiple strings.
"foo" + "bar" + "baz" "foo" + string_var + "baz" "+=" + string_var + "px"
Add a comment
var size = "680px"; $('#contactForm').animate({"marginLeft": "+="+size}, "slow");
You can use the + operator to concatenate your value in a variable to the "+=" string:
+
"+="
$('#contactForm').animate({"marginLeft": "+=" + size}, "slow");
var theWidth = "680px" $('#contactForm').animate({marginLeft: "+=" + theWidth}, "slow");
Required, but never shown
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.
Explore related questions
See similar questions with these tags.