eylay
eylay

Reputation: 2160

send Javascript variable to .css({transform: translate (var,var)})

I wanted to move a div 136px to right with transform property so i wrote: `

$(".the_div").css({"transform":"translate(136px,0px)"});

and the_div class contains

.the_div
{
  transition-duration:2s;
}

and it worked but now i want to send a javascript variable instead of 136px. is that possible? how can i do that? a variable like

var my_width = window.innerwidth * 0.1;

i wrote

$(".the_div").css({"transform":"translate(my_width+'px',0px)"});

and it obviously didnt work. do you have an idea to move a div One-tenth of screen width to right (using transform property)?

Upvotes: 1

Views: 6845

Answers (2)

Michiel J Otto
Michiel J Otto

Reputation: 2311

You can do this in pure Javascript as well using template strings. (PS - you don't even need JQuery)

First, save the div in a variable

const theDiv = document.querySelector('.the_div');

Second, save the value you want to translate in a variable

let number = 136;

Lastly, set the style attribute of the div

theDiv.style.transform = `tranlate(${number}px,0)`;

Hope this helps answer your question

Here is a helpful link for template strings https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Upvotes: 3

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

simply you just need concatenate variable in string in javascript " + my_width + "

$(".the_div").css({"transform":"translate(" + my_width + "px,0px)"});

Upvotes: 2

Related Questions