BlackMB
BlackMB

Reputation: 228

Use variables to set in style with javaScript

function Scale(){
    X = innerWidth / 1024;
    Y = innerHeight / 768;

    Z = document.getElementById("IFM");
    Z.style.transform = "scale(X, Y)";
}

I have a problem with this code. I couldn't use variables in scale!
What can I do with this problem?

Upvotes: 0

Views: 487

Answers (4)

Bergi
Bergi

Reputation: 665456

JavaScript has no inline string variables. All you can do is concatenate strings:

Z.style.transform = "scale("+X+", "+Y+")";

The numbers will be implicitly converted to strings.

You might as well use some custom sprintf-like format- or replace-methods, but usually concatenation with + is simpler.

Upvotes: 2

user2031802
user2031802

Reputation: 744

try this way "scale(" +X+ "," +Y+ ")";

Upvotes: 0

Austin Mullins
Austin Mullins

Reputation: 7437

Change that line to:

Z.style.transform = "scale(" + X +", "+ Y + ")";

Upvotes: 0

jAndy
jAndy

Reputation: 236162

You either build the string with concats / plus or use String.prototype.replace.

Z.style.transform = "scale(" + X + "," + Y + ")";

or with a helper like

String.prototype.sFormat = function _simpleFormat( map ) {
    var myString    = this.toString(),
        args        = map instanceof Array ? map : Array.prototype.slice.call( arguments );

    while( ~myString.indexOf( '%r' ) ) {
        myString = myString.replace( '%r', args.shift() );
    }

    return myString;
};

.. and then go like

Z.style.transform = "scale(%r, %r)".sFormat(X,Y);

Upvotes: 1

Related Questions