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?

5
  • 1
    possible duplicate of Dynamically changing less variables Commented Sep 17, 2015 at 2:25
  • @knitevision He's not talking about using built in less functions but creating his own custom ones. He can do that with backticks. Commented Sep 17, 2015 at 2:28
  • Thanks for your reply. Can I call the js fuction name directly in less file which function placed in a javascript file? Commented Sep 17, 2015 at 3: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.) Commented Sep 18, 2015 at 11:53
  • stackoverflow.com/questions/61328297/… same doubt i have anyone answer this? Commented Apr 21, 2020 at 16:55

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

2 Comments

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?
@Aji04 This will explain it better: bennadel.com/blog/…

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.