3

I have the following div

<div style="transform-origin: left top 0px; transform: translate3d(0px, -26px, 0px) scale(1);">

As you can see, transform contains scale(1). What's the best way to change scale value?

Thank you for your help.

2 Answers 2

8

Sure, using javascript. There are many ways to do it, I'd do it using a regex.

function changeScale(newScale){
    var div = document.getElementById('theID');
    var curTrans = div.style.transform;
    var newScaleString = 'scale(' + newScale + ')';
    var regex = /scale\([0-9|\.]*\)/;
    var newTrans = curTrans.replace(regex, newScaleString);
    div.style.transform = newTrans;
}

Or with less lines:

function changeScale(newScale){
    var div = document.getElementById('theID');
    div.style.transform = div.style.transform.replace(/scale\([0-9|\.]*\)/, 'scale(' + newScale + ')');
}
Sign up to request clarification or add additional context in comments.

2 Comments

@AndiPavllo Great :)
I've edited it not to repeat the terms "scale(" and ")" manually plus converted it to runnable code.
0

You could use a regular expression (assumed you have your div DOM element in a variable 'el' and want to change scale to 2):

el.style.transform.replace(/scale\(\d+\)/, 'scale(2)');

3 Comments

Unfortunately, unlike that answer this one suffers from multiple issues: it doesn't escape string brackets and assumes the scale multiplier is an integer and not floating.
Thanks for your remark about the brackets, @lwc, I changed that to prevent readers copy&paste wrong code. However, the OP didn't ask for a certain multiplier, but only for replacing the scale.
Nevertheless, I don't see any advantage.

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.