Search code examples
javascriptcssregexscalecss-transforms

Change "scale" attribute in CSS "transform"


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.


Solution

  • 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 + ')');
    }