Question

I using the less mixin which generate a random number within given range. here is the code:

.makeRandom(@min: 0, @max: @min+1) {
  // Math.floor(Math.random() * (max - min + 1)) + min
  @getNum: `(Math.floor(Math.random() * (@{max} - @{min} + 1)) + @{min})`;
}

and Calling in another mixin set animation on calling div:

.move (@left : 45% , @duration: 5s ,@delay : 2s) {
   animation: moveUp @duration linear @delay infinite;
   /* Safari and Chrome: */
   -webkit-animation: moveUp @duration linear @delay infinite ;
   .makeRandom(100,  400);
   margin-left:  unit(@getNum ,'px');
 }

but I am getting this error

SyntaxError: error evaluating function unit: the first argument to unit must be a number

when I tried to change the unit. how can I changed unit of @getnum?

Was it helpful?

Solution

I noticed this problem in v1.5.

Since v1.5 you can not pass non-numeric values (not passing isnumber()) to functions like unit() that accept only numbers as arguments, even though it worked in earlier versions.

And - numeric values in javascript interpolation were not recognized as numeric by LESS <= 1.6.0, and isnumber(`2`); would have returned false.

So, this two put together are the reason why numbers returned by javascript did not work in v1.5, but worked prior v1.5 and work again in LESS v1.6.


But if you need to use it in 1.5 you can "cast the type" by using a function that does accept strings or the "non-numeric numbers" returned by javascript interpolation:

@str: '230'; //or `230`
@getNum: (percentage(@str)/100);

this adds the percentage sign % at the end ... but it does not really matter if you just want to use it for the number ... as now you can pass it to any function that accepts only numbers ... in your case using unit() you can change the unit to whatever you like.

margin-left:  unit(@getNum , px);

However, an even simpler solution in your case would be to just skip the unit() function and concatenate the unit to @getNum:

margin-left:  ~'@{getNum}px';

The CSS output would in both cases look like this:

margin-left: 230px;

OTHER TIPS

I'm not sure if it was your case too, but since I landed on this page looking for an answer to the same error about 4 years later I decided to post this here so that it might help someone else in the same predicament 😊.

So, in our case we were getting this error in expressions like this:

width: unit(@navbarHeight - 0.1, em);

And the solution was to simply enclose the mathematical expression (in this case, subtraction) in parentheses, like this:

width: unit((@navbarHeight - 0.1), em);

@AsGoodAsItGets is right, as stated in the 4.0 changelog.

Parentheses are required (by default) around division-like expressions, to force math evaluation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top