0

I have a quick question: how can you add transforms as an inline style via JavaScript? For the last hour, I've been trying to solve this problem and also have been searching everywhere, but nothing worked. Here is my code:

HTML:

 <ul id="slider">
    <li class="slide"></li>
    <li class="slide"></li>
    <li class="slide"></li>
    <li class="slide"></li>
 </ul>

JavaScript:

 var windowWidth = $(window).width();
 var centerDistance = windowWidth / 2;
 var targets = $(".slide");
 var inlineTransform = '"' + "translateZ(" + centerDistance + "px)" + '"';
 for (var i = 0; i < targets.length; i++) {
     targets[i].style.WebkitTransform = inlineTransform;
     targets[i].style.msTransform = inlineTransform;
     targets[i].style.transform = inlineTransform;
 }

According to w3schools, nothing is spelled wrong and all the prefixes are correct: w3schools DOM style transform

The syntax should be correct too. I don't get any error messages and this code works if I use other styles.

2
  • 2
    You're adding quotes to the outside of your string. You don't need those. Commented Jun 20, 2017 at 21:05
  • 1
    "According to w3schools..." No! Bad! W3Schools is not an authoritative source of documentation, and has no affiliation with W3C, which is completely different. W3Schools has a history of inaccurate and poor documentation, as well as deceptive branding, and should not be trusted. Commented Jun 20, 2017 at 21:05

1 Answer 1

1

You don't need to add additional quotes to that string. A string is a string. Quotes are only needed for string literals inside code, and you already have those.

Here's a jQuery version:

var centerDistance = $(window).width() / 2;
var t = "translateZ(" + centerDistance + "px)";
var style = {
  WebkitTransform: t,
  msTransform: t,
  transform: t
};
$(".slide").css(style);
Sign up to request clarification or add additional context in comments.

1 Comment

Works like a charm! Thank you!

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.