Chabo
Chabo

Reputation: 3000

Using a JavaScript variable in a CSS transform

Just starting out with JS so this is likely a newbie question. I am trying to figure out how to use a JS variable when using this line of code in my JS:

But3.style.webkitTransform = "translateX(JSVARIABLE)";

In my JS file I am running a function when a button is hovered over:

HTML

<html>
<div id= "But3" class="Button3"> </div>
</html>

When this button is hovered over (mouseover), the function is run in my JS code here:

JS

But3.onmouseover = function(){

  var h = document.getElementById("But3").clientHeight;
  var w = document.getElementById("But3").clientWidth;

  var nh = Math.floor(Math.random() * h);
  var nw = Math.floor(Math.random() * w);

   /* This may be completely wrong*/
  var x = String(nh);
  var y = String (nw)

  /* This may also be completely wrong*/
  var nhf = x + "px";
  var nwf = y + "px";

  /* This works but I need it to work with nhf */
  But3.style.webkitTransform = "translateX(10px)";

}

How can I make it so that I can use my value nhf and nwf as the values for my translateX transform?

Note that I may be incorrectly formatting the values since I convert them to a string in order to include "px".

Here is my CSS if this is needed:

.Button3{
height: 20%;
  width: 17%;
  left: 30%;
  top: 20%;
  border-radius: 20%;
  background: #8585ad;
  margin: auto;
  position: relative;
  cursor: pointer;
  transition: 2s;
}

Upvotes: 1

Views: 2046

Answers (3)

TheWandererLee
TheWandererLee

Reputation: 1032

As jerrylow said, concatenate the variable into the string. This makes some of your excess code unnecessary

document.getElementById("But3").onmouseover = function(){

  var h = document.getElementById("But3").clientHeight;
  var w = document.getElementById("But3").clientWidth;

  var nh = Math.floor(Math.random() * h);
  var nw = Math.floor(Math.random() * w);

  // translateX should probably use nw instead of nh
  But3.style.webkitTransform = "translateX(" + nh + "px)";

}
<input type="button" value="Hover me" id="But3">

Upvotes: 2

vince
vince

Reputation: 8306

You can use string interpolation within a template literal to accomplish this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals.

In your case, that would look like:

But3.style.webkitTransform = `translateX(${nhf})`;

Template literals were introduced in the ES2015 specification and are supported by most major browsers.

Upvotes: 0

jerrylow
jerrylow

Reputation: 2629

You can concat the variable in your value:

 But3.style.webkitTransform = "translateX(" + nhf + ")";

Upvotes: 3

Related Questions