1

I have to call a JavaScript function from the less CSS for customization purpose. The function needs to pass the less variable from Less file to JS. is it possible to do it? using backtick can get JS variable in a Less file but I don't know how to call a JS function from less?

demo.js

function getGradient(colorlist, dark, light){
   // some large customization
}

demo.less

@color: #ffffff,#000000,#cccccc;
@light: 20%;
@dark: 50%;
@gradient : ~`getGradient(@{color}, @{light}, @{dark})`;

The above code is not working. Please let me know is it possible to access a JS function from Less?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Son04
  • 141
  • 3
  • 12
  • 1
    possible duplicate of [Dynamically changing less variables](http://stackoverflow.com/questions/7823204/dynamically-changing-less-variables) – knitevision Sep 17 '15 at 02:25
  • @knitevision He's not talking about using built in less functions but creating his own custom ones. He can do that with backticks. – Don Rhummy Sep 17 '15 at 02:28
  • Thanks for your reply. Can I call the js fuction name directly in less file which function placed in a javascript file? – Son04 Sep 17 '15 at 03:29
  • Well, in short (it's actually too many possible solutions): obviously the less compiler can't see your function in `demo.js` (how can it know that function is there and should be used at all?). You could try something like either `@plugin` or `less-plugin-funtions` or a sort of. Though to be honest I start to suspect this to be another akward XY-problem (I can't see any need for JS-based "some large customization" for whatever complex kind of gradient or whatever color lists in general.) – seven-phases-max Sep 18 '15 at 11:53
  • https://stackoverflow.com/questions/61328297/how-can-i-call-js-fun-from-less-file-and-get-js-object?noredirect=1#comment108493014_61328297 same doubt i have anyone answer this? – Mike Mohan Apr 21 '20 at 16:55

1 Answers1

3

You can embed javascript in lesscss files with backticks.

For example:

@myObject: `function(){

    var myObject = {
        getSomething: function() {
            return( "This is yo' content!" );
        }
    };

    return( myObject );

}`;

Notice the backticks (not single quotes).

Don Rhummy
  • 24,730
  • 42
  • 175
  • 330
  • Thanks for your reply. Can I call the javascript fuction name directly in less file like in my code snippet? `@gradient : ~`getGradient(@{color}, @{light}, @{dark})`;` The js function is placed in a separate js file. also can I pass some less variable in the javascript function? – Son04 Sep 17 '15 at 12:13
  • @Aji04 This will explain it better: http://www.bennadel.com/blog/2638-executing-javascript-in-the-less-css-precompiler.htm – Don Rhummy Sep 17 '15 at 15:32